[英]jquery - selecting unique id
i'm new to jquery 我是jquery的新手
i generated html div with php and give each them a unique id 我用PHP生成了html div并给每个人一个唯一的id
<div id=div1>text</div>
<div id=div2>text</div>
<div id=div3>text</div>
...
the problem is, how I select specific div with jquery? 问题是,我如何用jquery选择特定的div? usually i use this code to select an element
通常我使用此代码来选择元素
$('#id')
but I have to make alot of selector because each id is unique. 但我必须制作很多选择器,因为每个id都是唯一的。 Recently I used something like this
最近我用了这样的东西
<div ... onclick=getElem(id)></div>
function getElem(id){
var elem=$('#div'+id);
}
Is it good to use onclick
? 使用
onclick
好吗?
Add a class to the group of divs 将一个类添加到div组
<div id="div1" class="someClass">text</div>
<div id="div2" class="someClass">text</div>
<div id="div3" class="someClass">text</div>
...
Then in javascript: 然后在javascript中:
$('.someClass').click( function(event) {
var ele = $(this);
// ele is the element you clicked on
});
I can't tell what your real use-case is, but you shouldn't need the IDs anyway. 我不知道你的真实用例是什么,但你不应该需要ID。 Give all elements you want to handle clicks for a class:
提供您想要处理类的点击次数的所有元素:
<div class="some-group"></div>
<div class="some-group"></div>
<div class="some-group"></div>
Then just watch for clicks on the group: 然后只需查看该群组的点击次数:
$('.some-group').click(function(){
// do something with $(this).attr('id');
});
Add a class to the div elements: 在div元素中添加一个类:
<div id="div1" class="myDivClass">text</div>
<div id="div2" class="myDivClass">text</div>
<div id="div3" class="myDivClass">text</div>
Then you can iterate each element if you need to operate on each item separately 然后,如果需要分别对每个项目进行操作,则可以迭代每个元素
$('.myDivClass').each(function(){
// Process each item found that use the myDivClass
$(this).text("set a new text");
});
Or you can operate on all element at once 或者您可以一次操作所有元素
$('.myDivClass').text("set text on all elements");
This means that you can set a click callback to all using: 这意味着您可以使用以下命令设置单击回调:
$('.myDivClass').click(function(){
// Your click handler for ALL elements with myDivClass
});
or on each item separately, allowing to include some additional handling 或分别对每个项目,允许包括一些额外的处理
$('.myDivClass').each(function(){
// Here u could do some checks
var id = $(this).attr('id'); // or $(this).prop('id') // depends on jquery version
if(id !== "div1"){
$(this).click(function(){
// Click handler for each item
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.