【问题标题】:Using prototype to set an onclick event of a button?使用原型设置按钮的onclick事件?
【发布时间】:2012-04-30 22:15:58
【问题描述】:
我有这个按钮:
<button id="check_button" name ="check_button" type="button" onclick="setLocation('...')">
<span>check</span>
</button>
现在我知道我可以使用 $('check_button') 来访问它。有没有办法用 Prototype 设置setlocation 参数?
【问题讨论】:
标签:
javascript
button
onclick
prototypejs
dom-events
【解决方案1】:
function doButtonClick(event, element) {
console.log('event');
console.log('element');
// here, `element` is a reference to the button you clicked.
var elementId = element.identify();
// I'm not sure what setLocation takes in as a parameter, but...
setLocation(elementId);
}
$('check_button').on('click', 'button', doButtonClick);
这里是element.on 的文档:http://api.prototypejs.org/dom/Element/prototype/on/
这实际上只是一种创建新Event.Handler的快速方法:http://api.prototypejs.org/dom/Event/on/
请务必查看第二个文档链接 - 超级有用的东西。
【解决方案2】:
是的,
$('check_button').observe('click',this.setLocation.bind(this,'...'));
setLocation: function(param)
{
alert(param);
}
通过这种方式,参数将始终是您传递的内容。 “绑定”是一种拥有这种能力的多种强大方法。