使用$(this)关键字

时间:2018-02-15 12:26:10

标签: javascript jquery

我有几个盒子,每个盒子里面都有不同的标题和标题元素。

我想知道如何在已单击的相应框中获取所需元素的文本,而不是所有文本元素。

以下是我正在使用的内容:

 box.onclick = function(){
     alert($(this).text());
 };

这将显示警告框中的所有文本元素数据。我想单独定位一个具有id的指定文本元素,以便从中获取文本。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

You can use find() to target the child element:

$('.box').on('click', function() {
  console.log($(this).find('h3').text())
})
.box{
  background: #adadad;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='boxes'>
  <div class='box'>
    <h3>title 1</h3>
    <h4>subtitle 1</h4>
  </div>
  <div class='box'>
    <h3>title 2</h3>
    <h4>subtitle 2</h4>
  </div>
  <div class='box'>
    <h3>title 3</h3>
    <h4>subtitle 3</h4>
  </div>
</div>

答案 1 :(得分:-1)

<强> HTML

<div id = "content">
  <div id = "box">
    <p>This is the box content 1 </p>
  </div>
   <div id = "box">
    <p>This is the box content 2</p>
  </div>
</div>

<强> JS

$('*[id*=box]:visible').each(function(index) {
  $(this).click(function() {
    alert($(this).text());
  });
});

在此测试: https://codepen.io/bmvr/pen/WMZPXW