gpt4 book ai didi

jquery - 单击多个按钮之一,在文本输入中输入值

转载 作者:行者123 更新时间:2023-12-01 02:03:44 24 4
gpt4 key购买 nike

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

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

JavaScript 代码:

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

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

最佳答案

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
  • 您还可以在选择器上绑定(bind)一个 click 处理程序,而不是使用 each 进行循环。

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

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

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

关于jquery - 单击多个按钮之一,在文本输入中输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9115942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com