我有一个页面,其中有一个“获取路线”按钮'。标签的href是#,因此它是自我链接的。当用户点击此按钮时,我有一个脚本,如果链接仍设置为',则会阻止默认行为。然后,它使用来自URL的一些信息将ajax请求放到我的数据库中,以获取您正在查看其页面的公司的地址。然后使用地理位置来获取用户的位置,然后使用它来替换按钮的href属性。
当函数在document.ready上运行时,我完全正常工作,但浏览器会在单击按钮之前请求获取位置的权限,这是不可取的,因此我将其绑定到click事件。
我在所有内容的末尾调用触发器(单击),但它仍然阻止默认值。当我第二次单击一个按钮时,它会按预期执行,但我的触发器不起作用。我的问题是:有没有办法让它成功运行,触发器(点击)实际上就像第二次点击一样。我的代码如下。
<div class="row">
<div class="medium-11 medium-centered columns text-center">
<hr />
<a href="#" target="_blank" class="get-directions button" style="border-radius: 10px; font-family: oswald, sans-serif; FONT-SIZE: 14PT;">VIEW MAP & GET DIRECTIONS</a>
</div>
</div>
<script>
$('.get-directions').click(function(event) {
console.log($(this).attr("href"));
var linkHREF = $(this).attr("href");
console.log(linkHREF);
if (linkHREF == "#")
{
console.log("PREVENTED");
event.preventDefault();
var clientPID = window.location.href;
clientPID = clientPID.match(/\/webapp\/p\/[0-9]+/);
clientPID = clientPID[0].replace("/webapp/p/", "");
postData = {"pageID": clientPID};
var startingLocation;
var destination;
$.ajax({
dataType: "json",
data: postData,
type: "POST",
url: "/dealerLocator/getDirectionsButton.php",
success: compileAddress
});
}//END IF PREVENT
function compileAddress(jsonData)
{
destination = jsonData;
destination = destination.replace("#", "");
// check if browser supports geolocation
if (navigator.geolocation) {
if (navigator.geolocation.getCurrentPosition){
// get user's current position
navigator.geolocation.getCurrentPosition(function (position) {
// get latitude and longitude
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
startingLocation = latitude + "," + longitude;
// send starting location and destination to goToGoogleMaps function
goToGoogleMaps(startingLocation, destination);
});
}
}
}
// go to Google Maps function - takes a starting location and destination and sends the query to Google Maps
function goToGoogleMaps(startingLocation, destination) {
$getDirectionsLink = "https://maps.google.com/maps?saddr=" + startingLocation + "&daddr=" + destination;
$(".get-directions").attr("href", $getDirectionsLink);
console.log($(".get-directions").attr("href"));
$(".get-directions").trigger("click");
}
});
</script>
答案 0 :(得分:-1)
当你想要禁用默认事件时,只需return false
。