在JavaScript中的多个选择器中获取h4选择器的值 [英] Get value of a h4 selector inside multiple selectors in javascript

查看:136
本文介绍了在JavaScript中的多个选择器中获取h4选择器的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML中有一个ul列表,并且正在努力获取li元素的inner文本.我将稍微简化一下示例,以使您易于理解我正在尝试做的事情. 我有以下带有列表项的ul:

I have a ul list in HTML and I am struggling to get the inner text of the li element. I will simplify a little the example to be easy to understand what I am trying to do. I have the following ul with list items:

<ul id="table-history">
    <li class="item">
       <div class="item-row">
           <h4 class="item-title"> A </h4>
       </div>
     </li>

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> B </h4>
       </div>
     </li>        

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> C </h4>
       </div>
     </li>
</ul>

我已经在javascript中创建了click方法,当单击列表项时会触发该方法:

I have created a click method in javascript that get triggered when a list item is clicked:

$("#table-history > li").on("click", function () {

        console.log("Clicked");
});

如何获取<h4>元素内的文本?有什么方法可以单击链elements/views吗?

How can I take the text inside the <h4> element ? Is there a way how can I make the click on chain elements/views ?

推荐答案

您可以使用

$('h4.item-title' , this).text()

$("#table-history > li").on("click", function () {
        
        console.log($('h4.item-title' , this).text());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="table-history">
    <li class="item">
       <div class="item-row">
           <h4 class="item-title"> A </h4>
       </div>
     </li>

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> B </h4>
       </div>
     </li>        

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> C </h4>
       </div>
     </li>
</ul>

注意:最好使用.trim()避免空格

Note: It will be better to use .trim() to avoid white spaces

$('h4.item-title' , this).text().trim()

这篇关于在JavaScript中的多个选择器中获取h4选择器的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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