gpt4 book ai didi

javascript - 如何在点击时从按钮中获取值

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:14 27 4
gpt4 key购买 nike

我有一些按钮是根据当前电话号码的数量动态创建的。假设我在数据库中有 3 个名字,所以会有三个按钮。所以当我点击第一个按钮时,它应该给出值第一个按钮,如果单击第二个按钮,则应显示第二个按钮值。这很简单 jsfiddle这描述了我的要求。我想为每个按钮分配一个不同的 ID,它应该是电话号码。在 jsfiddle 中,当我单击特定按钮时弹出警报,但它没有给出任何值。

我喜欢这个

$('.btn').click(function(){ 
var number1 = $('#s2').val();
alert(number1);
});

最佳答案

您必须使用 jQuery's on() method 来使用事件委托(delegate).来自其文档:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

在您的情况下,您需要将 .btn 单击事件委托(delegate)给在将该元素动态添加到页面之前存在的祖先:

$('body').on('click', '.btn', function() {
var number1 = $('#s2').val();
alert(number1);
});

越接近 .btn 元素越好,因此除非您的文档的 body 是最近的非动态祖先,否则您需要更改它更接近一些。


编辑:评论中的进一步问题:

can I get the ID of each button

要获取每个按钮的id,只需使用this.id:

$('body').on('click', '.btn', function() {
var id = this.id;
alert(id);
});

编辑 2:评论中的进一步问题

So as I said,ID are numbers.So if i click button1 then it will print s1 in the inputfield.Can you please tell me how to do?

由于您的input 有一个“number”的id,您可以简单地使用jQuery 的.val() 方法来设置值input 到被点击按钮的 id:

$('body').on('click', '.btn', function(){ 
$('#number').val(this.id);
});

Working JSFiddle demo .

关于javascript - 如何在点击时从按钮中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19540564/

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