原型setAttribute()不使用$$()选择器

tin*_*esh 4 javascript prototypejs

我想更改div内的按钮onclick功能.HTML代码如下所示

<div class="buttons-set" id="payment-buttons-container">
    <button type="button" class="button" onclick="payment.save()" id="payment_button"></button>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在使用以下原型将onlick函数payment.save()更改为其他内容.

if(payment_method=='gate') {
   var e = $$('div#payment-buttons-container button.button');
   e.setAttribute('onclick','return false;'); // not working
} else {
    var e = $$('div#payment-buttons-container button.button');
    e.setAttribute('onclick','payment.save();'); // not working
}
Run Code Online (Sandbox Code Playgroud)

哪个不起作用并且说"Uncaught TypeError:Object [object HTMLButtonElement]没有方法'setAttribute'"但是当我通过静态获取按钮的id来使用此代码时

if(payment_method=='gate') {
    $('payment_button').setAttribute('onclick','return false;');// Works
}
else {
    $('payment_button').setAttribute('onclick','payment.save();');// Works
}
Run Code Online (Sandbox Code Playgroud)

其中"payment_button"是我拍摄的按钮的ID.

Gee*_* 88 10

问题是$$()返回与CSS选择器匹配的元素列表

如果您只想让第一个元素与选择器匹配,请尝试此操作

if(payment_method=='gate') {
   var e = $$('div#payment-buttons-container button.button')[0];
   e.setAttribute('onclick','return false;'); // not working
} else {
   var e = $$('div#payment-buttons-container button.button')[0];
   e.setAttribute('onclick','payment.save();'); // not working
}
Run Code Online (Sandbox Code Playgroud)

如果要将它应用于CSS选择器匹配的所有元素,请使用此invoke()方法执行此操作

if(payment_method=='gate') {
   $$('div#payment-buttons-container button.button').invoke('writeAttribute','onclick','return false;');
} else {
    $$('div#payment-buttons-container button.button').invoke('writeAttribute','onclick','payment.save();'); // not working
}
Run Code Online (Sandbox Code Playgroud)

我使用的原因writeAttribute(),而不是setAttribute()writeAttribute()是PrototypeJS方法会针对所有PrototypeJS支持浏览器,setAttbribute()是不是总是可用的标准方法.