jQuery jquery从动态创建的div中获取id值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21064724/
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 id value from dynamically created div
提问by Sivadinesh
<div id="tag<%=count++%>" value="val1">
<div id="tag<%=count++%>" value="val2">
<div id="tag<%=count++%>" value="val3">
Onclick event in jquery need to get value of the div. Exact number of divs created is dynamic
jquery中的onclick事件需要获取div的值。创建的 div 的确切数量是动态的
回答by Awlad Liton
You should use input instead of div:
您应该使用输入而不是 div:
Try this:
尝试这个:
Html :
网址:
<input type="text" id="tag<%=count++%>" value="val1"/>
<input type="text" id="tag<%=count++%>" value="val2"/>
<input type="text" id="tag<%=count++%>" value="val3"/>
Jquery:
查询:
$( document ).ready(function() {
$('input[id^="tag"]').on('click', function() {
alert(this.value);
});
});
using div:
使用 div:
try this:
尝试这个:
$( document ).ready(function() {
$('div[id^="tag"]').on('click', function() {
alert($(this).attr('value'));
});
});
回答by Afzaal Ahmad Zeeshan
First of all, value is not an attribute of div.
首先,value 不是 div 的属性。
But still you can use this:
但是你仍然可以使用这个:
var value = $('div').attr('value')
to get the ID attribute, and using that, you can get the value as:
获取 ID 属性,并使用它,您可以获得如下值:
$('#' + value).attr('id');
You can use it as a variable and then do what so ever!
您可以将其用作变量,然后执行任何操作!
回答by BenM
You can use the 'Attribute starts with' selector and then use this.id
:
$('div[id^="tag"]').on('click', function() {
alert(this.id); // Get the ID
alert($(this).attr('value')); // Get the value attribute
});
You should however note that value
isn't a valid attribute for <div>
elements. As such, it might be better to use data-value
, or use <input>
instead.
但是,您应该注意这value
不是<div>
元素的有效属性。因此,最好使用data-value
,或<input>
改为使用。