Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

jquery - 通过单击子类获取类的父ID(get parent id of a class from a click of the child class)

I have four <div> container as shown below:

(我有四个<div>容器,如下所示:)

 <div class="parentBox">
  <div class="childBox" id="20">
      <div>some content with in this div</div>
      <div>another div with more sontent</div>
  </div>
</div>

I want to get the childBox id into a jQuery variable when I click anywhere within the childBox div.

(我想在childBox div中的任何位置单击时将childBox id放入jQuery变量中。)

I've tried the following which gives me undefined

(我尝试了以下方法,这使我undefined)

 $('.parentBox').click(function (event) {
    var id = $(this).attr('id');
    console.log(id);
});

also tried this which gave me parent is not a function

(还尝试了这个给我父母不是一个功能)

var id = $(this).parent().attr('id');

and tried this which just gives me a blank in console log

(并尝试了这个,这在控制台日志中给了我空白)

var id = event.target.id;

Can someone please help?

(有人可以帮忙吗?)

  $('.parentBox').click(function (event) { var id = $(this).attr('id'); console.log(id); //does not work console.log($(this).parnet().attr('id')); //also does not work console.log(event.target.id); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parentBox"> <div class="childBox" id="20"> <div>some content with in this div</div> <div>another div with more sontent</div> </div> </div> 

  ask by Steve8428 translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want the .childBox id when clicking on .childBox div you can just hook the click event on the .childBox class:

(如果在单击.childBox div时需要.childBox id,则可以仅钩住.childBox类上的click事件:)

$('.childBox').click(function (event) {
    var id = $(this).attr('id');
    console.log(id);
});

EDIT:

(编辑:)

If you want to access the .childBox from .parentBox event you can do this:

(如果要从.parentBox事件访问.childBox.parentBox可以执行以下操作:)

$('.parentBox').click(function (event) {
    var id = $(this).find('.childBox').attr('id');
    console.log(id);
});

When dynamically adding children it's a good idea to hook the event on the parent or on the document object like this:

(动态添加子级时,最好将事件挂接到父级或文档对象上,如下所示:)

$(document).on('click', '.childBox' , function() {
  console.log($(this).attr('id'));
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...