jQuery 使用 .on() 事件获取 <a> 元素的哈希值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10840257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery get hash of <a> element using .on() event
提问by MaurerPower
Before I get flamed with references to manuals, I have been researching this for quite some time, and keep getting dead ends. Not even sure how to debug it properly. So if any references are cited, please ensure they are well-commented and instructional. This due to me being a PHP/mySQL developer, and the JavaScript object reference model is a bit confusing to me (but definitely doing my best to learn! :) ).
在我对手册的引用感到愤怒之前,我已经研究了很长一段时间,并不断陷入死胡同。甚至不确定如何正确调试它。因此,如果引用了任何参考文献,请确保它们得到了很好的评论和指导。这是因为我是一名 PHP/mySQL 开发人员,而且 JavaScript 对象参考模型让我有点困惑(但我肯定会尽力学习!:))。
I am trying to update my knowledge of jQuery using jQuery v1.7.2. Apparently the live event has been deprecated, and has been replaced by .on(). The jQuery docs say not to blend old 'click' or 'live' events with any scripts using .on().
我正在尝试使用 jQuery v1.7.2 更新我对 jQuery 的了解。显然,实时事件已被弃用,并已被 .on() 取代。jQuery 文档说不要将旧的“点击”或“实时”事件与使用 .on() 的任何脚本混合在一起。
While trying to get used to using on, I am trying to capture the hash of a given url.
在尝试习惯使用 on 时,我正在尝试捕获给定 url 的哈希值。
The page is as follows (header has already loaded jquery.min.1.7.2.js):
页面如下(header已经加载jquery.min.1.7.2.js):
<div id='menuHolder' style="position:relative; margin-left:50px;margin-bottom:30px; padding-top:35px; min-width:600px;z-index:998;">
<ul id="menu">
<li><a href="#">Events</a>
<ul id="events">
<li>
<img class="corner_inset_left" alt="" src="images/menu/corner_inset_left.png"/>
<a id="linker21 menu" class="test AJAXcaller" href="index.php#?p=1&d=AJAXcontent&i=1&k=<?=$_SESSION['authcpanel']['key']?>" rel="nofollow">Upcoming Events</a>
<img class="corner_inset_right" alt="" src="images/menu/corner_inset_right.png"/>
</li>
<li><a href="#">List All Events</a></li>
<li><a id="linkermenu" class="test AJAXcaller" href="index.php#?p=24&d=AJAXcontent&i=1&k=<?=$_SESSION['authcpanel']['key']?>" rel="nofollow">Add Events</a></li>
<li class="last">
<img class="corner_left" alt="" src="images/menu/corner_left.png"/>
<img class="middle" alt="" src="images/menu/dot.gif"/>
<img class="corner_right" alt="" src="images/menu/corner_right.png"/>
</li>
</ul>
</li>
</ul>
</div>
<script>
$(document).on("click", "a.AJAXcaller", function(){
alert("Goodbye!");
alert($(this).attr("hash"));
});
</script>
The first alert fires on clicking the 'Add Events' link (which has a hash), relays 'Goodbye!', then the second handler fires and relays 'undefined'. How would I access this hash?
第一个警报在单击“添加事件”链接(具有哈希值)时触发,转发“再见!”,然后第二个处理程序触发并转发“未定义”。我将如何访问这个哈希?
My old code is as follows, and it works, but any ajax called pages won't have event handlers attached, which is why I'm using the .on() event. Also, If I'm going to learn how to do it PROPERLY this time ;), I don't want deprecated functions involved...
我的旧代码如下,它可以工作,但是任何称为页面的 ajax 都不会附加事件处理程序,这就是我使用 .on() 事件的原因。另外,如果这次我要学习如何正确地做到这一点;),我不希望涉及弃用的功能......
OLD CODE(works)
旧代码(作品)
var linkClickAction = {
'a.AJAXcaller' : function(element){
element.onclick = function(){
var locationString = $(this).attr("hash");
locationString = locationString.replace(/.*\#(.*)/, "")
var parameterString = locationString.replace(/.*\?(.*)/, ""); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
var parameterList = new Array();
for (j = 0; j < parameterTokens.length; j++) {
var parameterName = parameterTokens[j].replace(/(.*)=.*/, ""); // j
var parameterValue = parameterTokens[j].replace(/.*=(.*)/, ""); // 1
parameterList[parameterName] = parameterValue;
}
var page = parameterList['p'];
var key = parameterList['k'];
var includesDir = parameterList['i'];
var changeDiv = parameterList['d'];
sndReq(page,key,includesDir,changeDiv,parameterString);
return false;
}
}
};
Behaviour.register(linkClickAction);
There was also a behaviour.js script loaded that basically handled the listener. I wasn't using jQuery at all at that time. It was nice, and FAST(tiny .js files, no extraneous code), comparatively speaking, but I hit my limit of being able to write effective JavaScript when it came to handling fancy things in my ui. So I have to load the jQuery script at page load anyways. Seeing as how it's already loaded, I'm trying to make use of it's functions instead of adding more unnecesarry scripts for my page to load. Thus I want to find a result that uses native jQuery 1.7.2 functions to accomplish this goal.
还加载了一个 behavior.js 脚本,它基本上处理了侦听器。那时我根本没有使用 jQuery。相对而言,这很好,而且速度很快(很小的 .js 文件,没有多余的代码),但是当谈到在我的 ui 中处理花哨的事情时,我达到了能够编写有效 JavaScript 的极限。所以我必须在页面加载时加载 jQuery 脚本。看看它是如何加载的,我试图利用它的功能,而不是为我的页面添加更多不必要的脚本来加载。因此我想找到一个使用原生 jQuery 1.7.2 函数来实现这个目标的结果。
RESULTS
结果
It turns out that jQuery 1.6+ can break when using the .attr() to find a property of a DOM object. So using .prop() was the way to go. Corrected code is as follows:
事实证明,当使用 .attr() 查找 DOM 对象的属性时,jQuery 1.6+ 可能会中断。所以使用 .prop() 是要走的路。更正后的代码如下:
/*
Page: rating.js
Created: Aug 2006
Last Mod: May 30, 2012
Modder: Darren Maurer
*/
function sndReq(page,key,includesDir,changeDiv,parameterString) {
var divToChange = document.getElementById(changeDiv); // the Div that the data will be put into
// switch Div with a loading div
divToChange.innerHTML = '<div class="loading"><img src="images/loading.gif" title="Saskatoon.CityGuru.ca - Loading Page" alt="Saskatoon.CityGuru.ca - Loading Page" border="0"/></div>';
if (includesDir == 1){
//Find Current Working Directory. Use to find path to call other files from
/*var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var arraytext = locarray.join("/");
*/
$.ajax({
type: "POST",
url: "AJAXCaller.php",
data: parameterString,
success: function(msg){
$('#'+changeDiv).html(msg);
}
});
}
}
/* =======END AJAX FUNCTIONS================= */
/* =======BEGIN CLICK LISTENER FUNCTIONS================= */
/* Listens to any a href link that has a class containing ' AJAXcaller' */
/* ie. <a id="link1" class="test AJAXcaller" href="index.php#http://233.help?id=22&think=33" rel="nofollow">> AJAX TEST LINK <</a> */
$(document).on("click", "a.AJAXcaller", function(){
alert($(this).prop("hash"));
var locationString = $(this).prop("hash");
locationString = locationString.replace(/.*\#(.*)/, "")
var parameterString = locationString.replace(/.*\?(.*)/, ""); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
var parameterList = new Array();
for (j = 0; j < parameterTokens.length; j++) {
var parameterName = parameterTokens[j].replace(/(.*)=.*/, ""); // j
var parameterValue = parameterTokens[j].replace(/.*=(.*)/, ""); // 1
parameterList[parameterName] = parameterValue;
}
var page = parameterList['p'];
var key = parameterList['k'];
var includesDir = parameterList['i'];
var changeDiv = parameterList['d'];
sndReq(page,key,includesDir,changeDiv,parameterString);
return false;
});
hope that helps someone, it definitely was a lifesaver for me!
希望对某人有所帮助,这对我来说绝对是救命稻草!
回答by Devin Crossman
Your a element doesn't have a hash attribute. try getting the href attribute and using javascript's substr and indexOf functions to split the string at the #
您的 a 元素没有 hash 属性。尝试获取 href 属性并使用 javascript 的 substr 和 indexOf 函数在 # 处拆分字符串
var href = $(this).attr("href");
var hash = href.substr(href.indexOf("#"));
You can also use
你也可以使用
$(this).prop("hash");
回答by Oleg
$('a.js-hash').click(function() {
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1000, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
// Prevent default anchor click behavior
return false;
});