【问题标题】:How can I retrieve the text of a clicked element using jQuery's .text property?如何使用 jQuery 的 .text 属性检索单击元素的文本?
【发布时间】:2013-12-06 10:15:42
【问题描述】:

我目前有一个所有具有唯一文本的 div 列表。我希望网站显示您刚刚在不同 div 中单击的 div 内的文本值。问题是,这个列表很长,而且我没有列表中任何值的特定 ID。是否可以使用$(this).text 从该列表中提取文本?我无法让它工作。

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Facilities Management</title>
    <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
    <script type='text/javascript' src='script.js'></script>
</head>
<body>
    <div class='wrap'>
        <div class='banner'>Facilities Management</div>
        <div class='menu1'>
            <div class='menu2'> Where do you live? <br><br>
                <div class='buildings'>building 1</div>
                <div class='buildings'>building 2</div>
                <!--- and so and so --->
            </div>
        </div>
        <div class='main'>
        <span id='jstext'></span>
        </div>
    </div>
</body>
</html>

JQuery:

$(document).ready(function() {
    $('.buildings').mouseenter(function() {
        $(this).css('background-color','#D8BFD8');
});
    $('.buildings').mouseleave(function() {
        $(this).css('background-color','#F0EAD6');
});
    $('.buildings').click(function() {
        var $buildingName = $(this).text;
        $('span').text($buildingName);
});
});

【问题讨论】:

    标签: jquery html text this


    【解决方案1】:

    text()是一个函数,需要调用它来获取被点击元素的文本

    var $buildingName = $(this).text();// <-- () at the end
    $('span').text($buildingName);
    

    你的代码可以改写为

    jQuery(function ($) {
        //these selectors are executed only once
        var $span = $('#jstext');
        $('.buildings').hover(function () {
            $(this).css('background-color', '#D8BFD8');
        }, function () {
            $(this).css('background-color', '#F0EAD6');
        }).click(function () {
            var buildingName = $(this).text();
            $span.text(buildingName);
        });
    });
    

    演示:Fiddle

    【讨论】:

      【解决方案2】:

      您已使用 text 作为属性。这是一个函数,所以像text()一样使用它

       var $buildingName = $(this).text();
      

      【讨论】:

        【解决方案3】:

        是的... text 是一个函数,使用 $(this).text();

        【讨论】:

          猜你喜欢
          • 2020-09-20
          • 1970-01-01
          • 2012-08-12
          • 1970-01-01
          • 1970-01-01
          • 2010-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多