如何将动态生成的锚标签的URL传递给jQuery hover()函数?
问题描述:
你好我想在这里做的是我生成的HTML链接的列表作为锚标签:如何将动态生成的锚标签的URL传递给jQuery hover()函数?
<a href="/path/100" id="clickme">One link</a>
<a href="/path/101" id="clickme">Sec link</a>
<a href="/path/102" id="clickme">Third link</a>
<a href="/path/103" id="clickme">Fourth link</a>
我想火Ajax
调用特定的URL,当有人对任何链接的徘徊。所以我注册hover()
功能,这样这个ID:
$('#clickme').hover(function(){
$.ajax({
beforeSend : function(jqXHR){
//Doin something
},
url: //should be the url from the anchor tag that fired this event(how to get it??),
success: function(data) {
//Doin something
},
error: function(jqXHR){
//Doin something
}
});
});
我的问题是如何传递锚标记为对象或东西,这样我可以取回任何我想要像href
,链接的位置
对于单锚标记它是工作,但对于多功能不..请帮助我。提前致谢。
答
ID应该永远是唯一的(这就是为什么它被称为ID)..让它类和使用类选择
HTML
<a href="/path/100" class="clickme">One link</a>
<a href="/path/101" class="clickme">Sec link</a>
<a href="/path/102" class="clickme">Third link</a>
<a href="/path/103" class="clickme">Fourth link</a>
jQuery的
$('.clickme').hover(function(){
var $this=$(this);
$.ajax({
beforeSend : function(jqXHR){
//Doin something
},
url: //should be the url from the anchor tag that fired this event(how to get it??),
data:{'href':$this.attr('href')}, //this will send '/path/100' as href if u click first link
success: function(data) {
//Doin something
},
error: function(jqXHR){
//Doin something
}
});
});
答
您应该使用class而不是将多个对象使用相同的id,并且对每个对象使用this.href
。尽管你可以做到这一点,但不允许给同一个id分配更多的html元素。
<a href="/path/100" id="clickme" class="someclass">One link</a>
<a href="/path/101" id="clickme" class="someclass">Sec link</a>
<a href="/path/102" id="clickme" class="someclass">Third link</a>
<a href="/path/103" id="clickme" class="someclass">Fourth link</a>
$('.someclass').hover(function(){
$.ajax({
beforeSend : function(jqXHR){
//Doin something
},
url: //should be the url from the anchor tag that fired this event(how to get it??),
success: function(data) {
//Doin something
},
error: function(jqXHR){
//Doin something
}
});
});
答
这不是因为ID是唯一的,jQuery只会查找ID的第一个实例。
<a href="/path/100" class="clickme">One link</a>
<a href="/path/101" class="clickme">Sec link</a>
<a href="/path/102" class="clickme">Third link</a>
<a href="/path/103" class="clickme">Fourth link</a>
JS
$('.clickme').mouseenter(function(){
var href = $(this).attr('href');
$.ajax({
url : href
});
});
答
您可以使用$(this)
里面,如果你的悬停事件处理程序来获取href属性。而其他答案是正确的使用类而不是id。下面的例子被设置为使用一类'clickme'而不是一个id。
$('.clickme').hover(function(){
var $this = $(this);
var theUrl = $this.attr('href');
$.ajax({
beforeSend : function(jqXHR){
//Doin something
},
url: theUrl
success: function(data) {
//Doin something
},
error: function(jqXHR){
//Doin something
}
});
});
好吧,但在我的悬停功能,如何获得特定的锚标签的细节? – Anubhab 2013-03-14 12:28:01
检查我的更新.... :) :) – bipen 2013-03-14 12:30:07
我不能直接给'url:$ this.attr('href')'? – Anubhab 2013-03-14 12:42:52