<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数是动态的
3 个解决方案
#1
9
You should use input instead of div:
您应该使用输入而不是div:
Try this:
尝试这个:
Html :
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:
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'));
});
});
演示
#2
4
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!
您可以将其用作变量,然后执行以下操作!
#3
0
You can use the 'Attribute starts with' selector and then use this.id
:
您可以使用'Attribute starts with'选择器然后使用this.id:
$('div[id^="tag"]').on('click', function() {
alert(this.id); // Get the ID
alert($(this).attr('value')); // Get the value attribute
});
jsFiddle演示
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不是
#1
9
You should use input instead of div:
您应该使用输入而不是div:
Try this:
尝试这个:
Html :
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:
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'));
});
});
演示
#2
4
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!
您可以将其用作变量,然后执行以下操作!
#3
0
You can use the 'Attribute starts with' selector and then use this.id
:
您可以使用'Attribute starts with'选择器然后使用this.id:
$('div[id^="tag"]').on('click', function() {
alert(this.id); // Get the ID
alert($(this).attr('value')); // Get the value attribute
});
jsFiddle演示
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不是