如何使用jQuery的.text属性检索单击元素的文本? [英] How can I retrieve the text of a clicked element using jQuery's .text property?

查看:73
本文介绍了如何使用jQuery的.text属性检索单击元素的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个所有具有唯一文本的div列表.我希望网站在您刚刚在其他div中单击的div中显示文本的值.事实是,此列表很长,并且列表中的任何值我都没有特定的ID.是否可以使用$(this).text从该列表中提取文本?我无法使它正常工作.

I currently have a list of divs that all have unique text. I would like the website to display the value of the text inside the div that you just clicked in a different div. The thing is, this list is very long, and I do not have specific IDs for any values in the list. Is it possible to pull text from that list using $(this).text? I could not get it to work.

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()是一个函数,您需要调用它才能获取被单击元素的文本

text() is a function, you need to invoke it to get the text of the clicked element

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);
    });
});

演示:小提琴

这篇关于如何使用jQuery的.text属性检索单击元素的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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