bind函数按钮的阵列的元件的情况下,“点击”(Bind function to the event

2019-10-17 11:50发布

序言:我是意大利人,对不起我的英语不好。

这是我的问题:

我想一个功能分配给一组按钮。

我需要一个参数传送给函数。

这是我试过的代码:

function test(atxt) {
    var buttons = $('.tblButton');

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].onClick(sayHello(atxt));
    }
}

function sayHello(txt){alert('hello' + txt)};

...收到以下错误:

Uncaught TypeError: Object #<HTMLButtonElement> has no method 'onClick'

你能告诉我在哪里出了错,我该如何解决?

编辑:我需要迭代,因为我需要“按钮的ID作为函数的参数,所以我需要做的buttons[i].onClick(sayHello(buttons[i].id))

Answer 1:

这会不会对你的工作,例如:你有另外一个原因迭代?

function test(atxt) {
    $('.tblButton').on('click',function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

或任选地,如果元件是静态的,存在:

function test(atxt) {
    $('.tblButton').click(function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

另一种方法:只需要改变这种风格:

var txt = "fred";
var atext = "hello" + txt;

function sayHello(atext) {
    alert(atext);
}
$('.tblButton').on('click', function() {
    sayHello(atext);
});
//below here just to demonstrate
$('.tblButton').eq(0).click();//fires with the fred
txt = "Johnny";// new text
atext = 'hello' + txt;
$('.tblButton').eq(1).click();//fires the Johnny

看到它在这里工作: http://jsfiddle.net/dFBMm/

因此,基于你的注意:此标记和代码:

<button class="tblButton" id="Ruth">Hi</button>
<button class="tblButton" id="Betty">Hi again</button>

$('.tblButton').on('click', function() {
    alert("Hello "+$(this).attr("id"));
});
$('.tblButton').eq(0).click();//fires with the Ruth
$('.tblButton').eq(1).click();//fires the Betty

http://jsfiddle.net/dFBMm/1/



Answer 2:

buttons[i].onClick(sayHello(atxt));

应该是

$(buttons[i]).on('click', function() { sayHello(atxt) });

如果你想获得当前按钮ID那么我认为你正在寻找这个..

for (var i = 0; i < buttons.length; i++) {
     $(buttons[i]).on('click', function() { sayHello(this.id) });
}


Answer 3:

如果你想通过所有按钮的迭代,那么你必须这样做与.each() jQuery的的处理程序:

$(function(){
  $(".tblButton").each(function () {
    $(this).click(function(){
       alert($(this).attr('id'));
    }); 
  });
});

检出jsbin: http://jsbin.com/usideg/1/edit



文章来源: Bind function to the event “onclick” of the elements of an array of buttons