【问题标题】:Click one of multiple buttons, put value in text input单击多个按钮之一,在文本输入中输入值
【发布时间】:2012-02-03 00:43:24
【问题描述】:

我在这里做错了什么 (http://jsfiddle.net/dsqBf/2/)?

我正在尝试将单击按钮的值放入文本输入中。如果单击任何按钮,则最后一个按钮的值将插入到文本输入中。

JavaScript 代码:

var theButtons = $(".button");
$(theButtons).each(function(index) {
    currentButton = $(this);
    buttonValue = currentButton.val();
    currentButton.click(function() {
        $("#theinput").val(buttonValue);
    });
});

我是否遗漏了一个我不知道的概念?谢谢!

【问题讨论】:

    标签: jquery


    【解决方案1】:

    前缀currentButton var。没有它,变量的值将被分配给全局范围内的变量,因为您没有在其他任何地方声明currentButton。因此,currentButton 的值更改为最后一个按钮的值(因为只有一个变量)。

    var theButtons = $(".button");
    theButtons.each(function(index) {
        var currentButton = $(this);
        var buttonValue = currentButton.val();
        currentButton.click(function() {
            $("#theinput").val(buttonValue);
        });
    });
    

    其他说明:

    • thebuttons 已经是一个 jQuery 对象,所以你不应该再次将它包裹在 $ 中。
    • $("#theinput") 可能不会随着时间而改变。所以,我建议缓存这个变量。
    • 另一方面,当前按钮的值可能会改变。我建议在点击处理程序中使用this.value
    • 除了使用each 循环之外,您还可以在选择器上绑定click 处理程序。

    推荐代码(演示:http://jsfiddle.net/dsqBf/11/

    var $theButtons = $(".button");
    var $theinput = $("#theinput");
    $theButtons.click(function() {
        $theinput.val(this.value);
    });
    

    $ 为前缀的jQuery 变量,因为这是惯例。因为$,你(和其他人)知道这个变量是一个jQuery对象,这样可以节省昂贵的调试时间。

    【讨论】:

    • 非常感谢。 “缓存这个变量”是什么意思?
    • @sloopjohnB 如答案底部所示,将 jQuery 对象存储在 loop.click 处理程序之外的变量中。
    【解决方案2】:

    您使用的是 .each() 而不是基本的 .click()。查看我的更新。

    http://jsfiddle.net/dsqBf/3/

    var theButtons = $(".button");
    
    $(theButtons).click(function() {
        $("#theinput").val($(this).val());
    });
    

    【讨论】:

      【解决方案3】:

      您遇到类似于closure-in-a-loop problem 的情况,因为您的变量是全局
      在执行事件处理程序时,它将访问 buttonValue,其中包含来自 each 循环的最后一次迭代的值。

      有两种方法可以解决这个问题:您可以通过添加 var 将变量设置为本地变量,或者将代码重写为:

      $(".button").click(function() {
          $("#theinput").val($(this).val());
      });
      

      【讨论】:

        【解决方案4】:

        你应该这样做

        var theButtons = $(".button");
        
        theButtons.click(function(index) {
            var currentButton = $(this);
            var buttonValue = currentButton.val();
        
          $("#theinput").val(buttonValue);
        
        });
        

        在这里摆弄http://jsfiddle.net/dsqBf/6/

        【讨论】:

          猜你喜欢
          • 2021-05-14
          • 1970-01-01
          • 2015-10-27
          • 2018-09-23
          • 2021-12-08
          • 1970-01-01
          • 2021-12-12
          • 1970-01-01
          • 2014-02-27
          相关资源
          最近更新 更多