【问题标题】:JQuery and using $(this) to access attributesJQuery 并使用 $(this) 访问属性
【发布时间】:2017-01-08 16:30:27
【问题描述】:

您好,我正在开发一个计算器。目前我被卡住了......我正在使用 jquery on(click) 功能,所以当一个数字被按下时,我可以尝试将它打印到屏幕上。所有数字都有相同的数字类,所以我使用 $(".digit").on("click", function ());

每个数字也有 id 和一个值,但我很难使用“this”变量来访问该属性。请看下面的sn-p。

    <div id="calculator">
        <div id="screen"></div>
        <div id="buttons">
            <button id="clear" onclick="clear()">C</button>
            <button class="digit" id="1" value="1">1</button>
            <button class="digit" id="2" value="2">2</button>
            <button class="digit" id="3" value="3">3</button>
            <button class="digit" id="4" value="4">4</button>
            <button class="digit" id="5" value="5">5</button>
        </div>
   </div>

$(document).ready(function () {    
    $(".digit").on("click", function () {
        $("#screen").append($("this").attr("value"));
    });
});

【问题讨论】:

  • 为什么“this”两边要加引号?
  • this 不应该是字符串。
  • 哦,那么问题解决了!

标签: jquery this


【解决方案1】:

改变这个:

$("this").attr("value")

到这里:

$(this).val()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2013-12-15
    • 2014-04-18
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多