jquery - 如何使用 jQuery 的 .text 属性检索单击元素的文本?

标签 jquery html text this

我目前有一个 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);
});
});

最佳答案

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

关于jquery - 如何使用 jQuery 的 .text 属性检索单击元素的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20421330/

相关文章:

jquery - 使用 jquery 多次追加表

android - 使用 Canvas 获取文本的高度和宽度

PHP file_get_contents 添加空格?

Javascript在对象数组内查找整数属性值

javascript - 当函数名称为字符串时,如何调用函数并传递参数?

c# - 显示总行数 Grid.MVC 列表的最佳方式

html - 如何在 li 内联中显示 ul?

html - 是什么导致两个具有相同计算样式的 html 元素在显示上有所不同?

R - 'NA' 文本被视为 N/A

jquery - Bootstrap Modal 无法在 IE 中工作,尝试了 Stack 上的所有其他解决方案