在 Jquery 中,你如何找出被点击的元素的“eq”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1188760/
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
In Jquery how do you find out the 'eq' of an element of what is being clicked?
提问by Stephen
When one of the divs inside 'uploadChoice' is clicked, how can I ascertain which one is clicked? Can I return an 'eq' value somehow?
单击“uploadChoice”中的其中一个 div 时,如何确定单击了哪个 div?我可以以某种方式返回 'eq' 值吗?
<div id=uploadChoice>
<div>Text</div>
<div>Image</div<
<div>Text & Image</div>
</div>
$("#uploadChoice div").click(function(){
//insert code here! :)
});
回答by brianng
$('#uploadChoice div').click(function(event) {
var index = $(this).index();
});
回答by redsquare
An easier alternative that does not require duplicating a selector is the following
不需要复制选择器的更简单的替代方法如下
$('#uploadChoice div').click(function(event) {
var index = $(this).prevAll().length;
});
回答by NinoMarconi
You can add selectors as well, and pass "$(this)" as argument:
您也可以添加选择器,并将“$(this)”作为参数传递:
$(document).on('click', 'button.testbutton', function () {
var index = $('div.example > div.xyz').find('button.testbutton').index($(this));
});
回答by idrumgood
You can get the contents of the div with
您可以使用以下方法获取 div 的内容
$("#uploadChoice div").click(function(){
var choice = $(this).html;
}
And then just do a switch statement or some nested ifs.
然后只做一个 switch 语句或一些嵌套的 ifs。
Personally though, I'd add an ID to each of the divs and just check the ID of the clicked element.
不过就我个人而言,我会为每个 div 添加一个 ID,然后只检查单击元素的 ID。