用jquery获取元素id [英] Getting element id with jquery

查看:91
本文介绍了用jquery获取元素id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码应该打印所选div的id,但它不会。我没有发现错误。感谢您的帮助。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆