【问题标题】:how to use jquery to get value out of div如何使用jquery从div中获取价值
【发布时间】:2012-05-15 15:26:30
【问题描述】:

如何使用 Jquery 获取 div 的内容。

这是我的 HTML:

<div class="DataRow" data-vendorid="67">
    <div class="DataColumn" style="width: 60%;">
        Barracuda
    </div>
    <div class="DataColumn" style="width: 20%; text-align: center;">
        1
    </div>
    <div class="DataColumn" style="width: 20%; text-align: center;">
        2
    </div>
</div>

这是我的 Jquery:

$(function () {
    $('.DataRow').click(function () {
        // get value: Barracuda 
    });
});

【问题讨论】:

  • .DataRow div 里面有 3 个 div。你想得到第一个 div 值吗?如果你想要梭子鱼,你可以在孩子上使用 :first 并得到它 .text()
  • 已全部回答:How to find an element within an element。 jQuery selector 和 traversal 包含有关可用于查找特定元素的所有方法的信息。那就看看Select inner text (jQuery)吧。
  • 一开始我也觉得这是重复的,但鉴于他在 sub-div 上没有唯一的类,我认为这对于 JQuery 初学者来说是一个棘手的问题,而且不会立即显现出来关于如何解决/什么关键字归零。

标签: javascript jquery html


【解决方案1】:
$(function () {
    $('.DataRow').click(function () {
        alert($(this).find(':first-child').text());
    });
});

或者:

$(function () {
    $('.DataRow').click(function () {
        alert($(this).children().first().text());
    });
});

【讨论】:

    【解决方案2】:

    如果您需要获取点击的 div 的内容,它可能会对您有所帮助。

    $(function () {
        $('.DataRow').click(function (event) {
    
            alert(event.target.innerHTML);
        });
    });​
    

    DEMO 1

    如果只需要获取第一个值:

    $('.DataRow').click(function () {
        var first = $(this).children().eq(0).html();
        alert(first);
    });​
    

    DEMO 2

    【讨论】:

      【解决方案3】:

      如果您只需要获取“Baracuda”,即第一个 div 文本,您可以像这样使用 innerHTML:

      $(function () {
          $('.DataRow').click(function () {
              // get value: Barracuda 
              alert($(this).children("div")[0].innerHTML);
          });
      });​
      

      这是example。

      【讨论】:

      • 您在网址中的示例是绝对错误的。请修改。
      【解决方案4】:

      你也可以这样用:

      var value=$(".DataColumn").html();
      

      【讨论】:

        【解决方案5】:

        获取first子元素的内容:

        $('.DataRow').click(function () {
            var first = $(this).children(":first").html();
        });
        

        获取第三个​​子的内容:

        $('.DataRow').click(function () {
            var third = $(this).children(":eq(2)").html();
        });
        

        【讨论】:

          猜你喜欢
          • 2023-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-13
          • 1970-01-01
          • 1970-01-01
          • 2011-02-25
          • 2018-01-12
          相关资源
          最近更新 更多