用jquery获取元素id [英] Getting element id with jquery
问题描述
HTML
< body>
< div id =form_area>
< div>
< button onclick =return add_row(); style =width:100%;>添加行< / button>
< / div>
< / div>
< / body>
Javascript
$(document).ready(function(){
$('#form_area div')。click(function(e){
console.log($(this).attr 'id'));
});
});
function add_row(){
var random_id = Math.floor((Math.random()* 1000)+ 1);
$('#form_area')。prepend('< div id ='+ random_id +'class =form_row>< / div>');
}
你错过了什么。您正在尝试使用 add_row
函数添加一行记录 ID
,
.form_row
会动态添加到DOM。因此,当执行 $('。form_row')。click(
,没有 .form_row
来绑定处理程序。以下使用 .on
方法的方法将处理程序绑定到 #form_area
,并仅在click事件发生时执行处理程序从 .form_row
$('#form_area')。on 'click','.form_row',function(){
console.log(this.id);
});
$('#form_area div')
选择<$ c $在div #form_area
中没有 ID
p>
在html中显示下面的评论显示哪个div被选中,
< div id =form_area>
< div><! - $('#form_area div')选择此div - >
< button onclick =return add_row(); style =width:100%;>添加行< / div>
< / code> $< / $>
< / div>
< p $ p>
The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.
HTML
<body>
<div id="form_area">
<div>
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
</body>
Javascript
$(document).ready(function() {
$('#form_area div').click(function(e) {
console.log($(this).attr('id'));
});
});
function add_row() {
var random_id = Math.floor((Math.random() * 1000) + 1);
$('#form_area').prepend('<div id="' + random_id + '" class="form_row"></div>');
}
解决方案 Ok, I think I understand what you are missing. You are trying to log the ID
after adding a row using add_row
function,
.form_row
is added dynamically to the DOM. So when executing $('.form_row').click(
, there is no .form_row
to bind the handler. The below way of using .on
method binds the handler to #form_area
and executes the handler only when the click event is from .form_row
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
$('#form_area div')
selects the div
inside the div #form_area
which doesn't have an ID
Below comment in html shows which div is selected,
<div id="form_area">
<div> <!-- $('#form_area div') selects this div-->
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
这篇关于用jquery获取元素id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!