如何让jQuery事件在直接链接到http://www.website.com/#id?
试图找出如何让jQuery检测引用页面上唯一ID的超链接。我不仅想在页面上单击元素时加载事件,还想在有人使用分配给该div的唯一#id直接链接到页面时加载事件 更新: 好的,这就是我目前所知道的,它没有开火如何让jQuery事件在直接链接到http://www.website.com/#id?,jquery,html,events,hyperlink,Jquery,Html,Events,Hyperlink,试图找出如何让jQuery检测引用页面上唯一ID的超链接。我不仅想在页面上单击元素时加载事件,还想在有人使用分配给该div的唯一#id直接链接到页面时加载事件 更新: 好的,这就是我目前所知道的,它没有开火 function opencontact() { $("#first-name-check").hide(); $("#last-name-check").hide(); $("#phone-number-check").hide();
function opencontact() {
$("#first-name-check").hide();
$("#last-name-check").hide();
$("#phone-number-check").hide();
$("#email-address-check").hide();
$("#customer-message-check").hide();
$("#send").button("disable");
$("#email-form").dialog("open");
}
$(".email").click(opencontact);
var hash = window.location.hash.substring(1);
alert(hash);
if (hash == "contact") {
opencontact();
}
Alert正在返回正确的散列,因此我不知道出了什么问题
对话框初始化如下:
$(function() {
$("#email-form").dialog({
autoOpen: false,
resizable: false,
draggable: false,
closeOnEscape: false,
height: 600,
width: 540,
modal: true,
buttons: {
"Send Joe Your Message": {
text: "Send Joe Your Message",
id: "send",
click: function() {
$.post("email.php", $(this).find('input, textarea').serialize());
$(this).find('input, textarea').val("");
$(this).dialog("close");
},
},
Cancel: function() {
$(this).find('input, textarea').val("");
$(this).dialog("close");
}
}
});
});
您可以这样做:
$(document).ready(function() {
// Attach click handlers and set your dialog here..
if(window.location.hash.length > 1) {
switch(window.location.hash) {
case '#contact':
$('.email').click();
break;
case '#anyotheridyouvegot':
$('.classoftheelementtobeclickedon').click();
break;
}
}
});
这将在页面加载时检查
url
中是否有散列,然后根据散列值触发对元素的id
单击。类似的操作应该可以:
//this will grab the url from the address bar
var oldUrl = document.location.href;
//now we need to find just the part after the #
var urlSlice = oldUrl.split('#',oldUrl.length);
//urlSlice is now an array of two items (one before the '#' one after)
//from which we can grab the div id
var divId = urlSlice[1];
//then if it is the id you want
if( divId === 'desiredID' ) {
clickHandler();
}
function clickHandler() {
//do stuff
}
就我个人而言,我会将所有这些都放在一个函数中以使其更干净,但它也会在一个函数之外工作。我认为您可能希望从url获取查询字符串,然后在dom就绪事件上触发事件检查字符串值,然后调用您的函数。您可能希望在更新中检查此链接,您正在将散列传递给一个不接受参数的函数。@user1846192:很公平,但请忽略这一点,我只是在测试一些东西。。没有它它就不能工作。对话方法是什么?新HTML5?@hayonj:jQuery用户界面,如图所示:这对我很有用。您确定它正在传递if语句吗?