【问题标题】:How to complete the href in the <a> tag with javascript如何用javascript补全<a>标签中的href
【发布时间】:2012-05-05 02:57:00
【问题描述】:

编辑

我想知道如何使用 Javascript 完成锚标记中的 href。 我有以下功能可以返回我的经度和纬度。

   function(obj){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(userPosition,errorPosition);
    }else {
        alert('Geolocation is not available');
    }
    function userPosition(position){
        obj.setAttribute('href', 'http://maps.google.com/maps?  daddr=~ITEM.STREET~,+~ITEM.CITY~&saddr=' + position.coords.latitude +  ',' position.coords.longitude);  
    }
    function errorPosition(error){
        switch(error.code){
            case eror.PERMISSION_DENIED:
                alert('permission denied');
                break;
        }
    }
}

在这里我得到我当前的位置他的纬度和经度作为警报。 但我想做的是以下。目前我有这个。

  <a class=localization href="#" onclick="geo(this)">
                <img src="images/localizationIcon.png" width=35 height=45 />
            </a>

当我点击图片时,我想要那个。经纬度填写在我的href中。

有人可以帮帮我吗?

亲切的问候。

史蒂夫

【问题讨论】:

  • 这些值会在不影响服务器的情况下动态变化吗?

标签: javascript html css anchor href


【解决方案1】:

onclick="geo()" 更改为onclick="geo(this)"

function geo() 更改为function geo(obj)

将 userPosition 的警报替换为:

obj.setAttribute('href', 'http://maps.google.com/maps?  daddr=~ITEM.STREET~,+~ITEM.CITY~&saddr=' + position.coords.latitude +  ',' + position.coords.longitude);

您必须对此进行调整以匹配 Google 地图格式。我不确定他们想要的地址是什么,但我很确定在这种情况下您指定的是街道地址,而不是纬度/经度组合..

【讨论】:

  • 如果函数以锚点作为上下文调用,则不需要将this 作为参数传递。你可以在你使用obj的函数中引用this
  • 你没有,但也没有伤害。
  • 当然可以,但它会让下一个开发人员假设您不了解范围。这就像打电话给geo.call(this, this),这很奇怪。
  • 我应该在我的锚标签中的 href 中添加什么?
  • @JordanMcGuigan 小错字。您的obj.setAttributeposition.coords.longitude 之前缺少+
【解决方案2】:

我会存储整个网址并替换整个内容。

var url = "google.com/maps?etc";
var newval = "google.com/maps?etc&ll"+long+","+lat;
element.href = newval;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2011-10-30
    • 2015-08-01
    • 2020-01-12
    • 1970-01-01
    • 2021-03-03
    • 2018-05-20
    相关资源
    最近更新 更多