单击多个按钮之一,将值放入文本输入 [英] Click one of multiple buttons, put value in text input

查看:62
本文介绍了单击多个按钮之一,将值放入文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What am I doing wrong here (http://jsfiddle.net/dsqBf/2/)?

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

I'm trying to put the value of the clicked button into the text input. If you click any button, the value of the last button is inserted into the text input.

JavaScript代码:

JavaScript code:

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

我错过了一个我不知道的概念吗?谢谢!

Am I missing a concept I'm not aware of? Thanks!

推荐答案

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

Prefix currentButton by var. Without it, the variable's value will be assigned to a variable in the global scope, because you haven't declared currentButton anywhere else. Consequently, the value of currentButton is changed to the value of the last button (because there's only one variable).

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

  • 而不是使用每个,你也可以在选择器上绑定点击处理程序。

  • thebuttons is already a jQuery object, so you should not wrap it in $ again.
  • $("#theinput") does probably not change over time. So, I recommend to cache this variable.
  • The value of the current button, on the other hand, may change. I suggest to use this.value inside the click handler.
  • Instead of looping using each, you can also bind a click handler on the selector.
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
    $theinput.val(this.value);
});

带有 $ ,因为这是惯例。由于 $ ,您(和其他人)知道该变量是一个jQuery对象,这节省了昂贵的调试时间。

Prefixed jQuery-variables with $, because it's the convention to do so. Because of $, you (and others) know that the variable is a jQuery object, which saves expensive debugging time.

这篇关于单击多个按钮之一,将值放入文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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