jQuery click()将href添加到a-tag

时间:2013-10-30 11:21:09

标签: jquery url javascript-events geolocation attr

当我点击GPS-link时,我尝试在url标记中实施a。 但它不起作用!

jQuery的:

$(document).ready(function(){

  /* add geolocation */
  $("a.target").click(function(){
    if(navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
       alert("Geolocation is not supported by this browser.");
    }
  }
  function showPosition(pos){
     var lat = pos.coords.latitude;
     var lon = pos.coords.longitude;

     /* GPS link */
     $("a.target").attr("href", 
            "http://dev.market-locator.com/geolocation-lijst?distance[latitude]="
            + lat + "&distance[longitude]=" + lon
            + "&distance[search_distance]=20&distance[search_units]=km");
   }

});

HTML:

...
<a class="target">Link</a>
...

3 个答案:

答案 0 :(得分:1)

你的jQuery代码应该是这样的:

$(document).ready(function(){

      /* add geolocation */
      $("a.target").click(function(){
        if(navigator.geolocation) {
          showPosition(navigator.geolocation.getCurrentPosition());
        }
        else
        {
          alert("Geolocation is not supported by this browser.");
        }
      });
  });

 function showPosition(pos){
    var lat = pos.coords.latitude;
    var lon = pos.coords.longitude;

    /* GPS link */
    $("a.target").attr("href", "http://dev.market-locator.com/geolocation-lijst?distance[latitude]=" + lat + "&distance[longitude]=" + lon + "&distance[search_distance]=20&distance[search_units]=km");
    window.location.href = "http://dev.market-locator.com/geolocation-lijst?distance[latitude]=" + lat + "&distance[longitude]=" + lon + "&distance[search_distance]=20&distance[search_units]=km"; //add this line
}

应在.ready()函数之外定义函数。

答案 1 :(得分:0)

您的showPosition函数需要参数pos,但它不会在通话时收到。

也许,这样的事情会起作用吗?

showPosition(navigator.geolocation.getCurrentPosition());

答案 2 :(得分:0)

首先,可能是因为您没有正确关闭点击功能:

  $("a.test").click(function(){
    if(navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      alert("Geolocation is not supported by this browser.");
    }
  });