jQuery:从类中获取 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1894129/
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 ids from class
提问by Hyman
I have a lot of div's and I want to fade this one who is hovered.
How i can get the id of the hovered div?
Is there anyway to do that except calling function(and sendind the id) with "onmouseover"?
Thanks!
我有很多 div,我想淡化这个悬停的 div。
我如何获得悬停的 div 的 id?
除了使用“onmouseover”调用函数(并发送id)之外,还有其他方法吗?
谢谢!
回答by ThoKra
try something like
尝试类似
$(".classes").mouseover(function() {
$(this).function();
};
to get the ID of an element you use the attr function
使用 attr 函数获取元素的 ID
$('.name').attr('id');
回答by ShivarajRH
On hover on these div's...
悬停在这些 div 上...
HTML:
HTML:
<div class="add_post_cmmnt" id="box-100" >Box1</div>
<div class="add_post_cmmnt" id="box-200" >Box2</div>
<div class="add_post_cmmnt" id="box-400" >Box3</div>
JavaScript:
JavaScript:
$(".add_post_cmmnt").hover(function(e) {
var id = this.id; // Get the id of this
console.log("id is " + id); //Test output on console
$('#pid').val(id); // Set this value to any of input text box
$(this).fadeOut(400); // Finally Fadeout this div
});
回答by Mariano Cavallo
You could set a class to flag the divs after you applied the animation so you can easily identify hovered divs.
您可以在应用动画后设置一个类来标记 div,以便您可以轻松识别悬停的 div。
(function($){
$.fn.extend({
myDivHover: function(){
var $set = $(this);
return $set.each(function(){
var $el = $(this);
$el.hover(function(){
fadeOutAnimation( $el, $set );
}, function(){
fadeInAnimation( $el );
});
});
}
});
function fadeOutAnimation( $target, $set ){
// Revert any other faded elements
fadeInAnimation( $set.filter('.hovered') );
// Your fade code here
...
...
// Flag
$target.addClass('hovered');
}
function fadeInAnimation( $target ){
// You revert fade code here
...
...
// Unflag
$target.removeClass('hovered');
}
})(jQuery);
// Apply it to the divs with XXX class
$('div.XXX').myDivHover();
// Select hovered item
var theID = $('div.XXX').filter('.hovered').attr('id');
Hope it helps :)
希望能帮助到你 :)