![](/img/trans.png)
[英]dynamically generated js buttons with closures to assign onclick function parameters
[英]How to pass parameters into onclick function parameters into dynamically created buttons?
我的javascript从文件中读取文本,并根据下面的按钮创建动态创建按钮。 我面临的问题是它无法在点击时调用该功能。 我已经尝试删除参数来调用它,它可以工作,但我似乎无法让它与传递参数一起工作。 有人可以帮我吗?
JS:
function toggleVisibility(type){
alert(type);
}
按钮创建:
var button='<button type="button" class="btn btn-block btn-inverse active" data-toggle="button tooltip" title="Click this to enable/disable viewing of '+this+'" onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';
首先,您不应该使用内联处理程序,并且使用jQuery创建它更容易:
var that = this;
var button = $("<button>");
button.addClass("btn btn-block btn-inverse active");
button.attr({
type: "button",
"data-toggle": "button tooltip",
title: "Click this to enable/disable viewing of " + that
});
button.text(word);
button.on("click", function () {
toggleVisibility(that);
});
(是的,我知道你可以链接所有的方法调用,我只是想这样做)
当你准备把这个按钮放在某处时,只需使用$container.append(button);
。
一切都取决于this
是什么或你想要/期望它是什么。 如果你需要传递给toggleVisibility
的参数成为刚刚点击的特定按钮(我猜是要切换它的可见性),只需传递this
(忽略that
)。 至于设置title
属性,我不确定你想要什么:)
如果你有一个HTML结构,如:
<div id="container">
<!-- Buttons go somewhere in here -->
</div>
并且您将按钮附加到该容器(或该容器中的某个位置),使用事件委派将单个click
处理程序绑定到容器会更有效:
$("#container").on("click", ".special-btn-identifier", function () {
toggleVisibility(this);
});
当然,您需要在按钮中添加“special-btn-identifier”类,以便此事件处理程序可以工作(并删除每个按钮的各个click
处理程序,因为这将覆盖它们)。 这个单一事件处理程序只需要运行一次,最好只要#container
就绪就好......就像$(document).ready(function () {});
。
替换以下行:
.. onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';
对于这一个:
.. onclick="toggleVisibility(this)">'+word+'</button>';
因为你不需要逃避this
关键字,也包括不同this
从那里你正在创建按钮文本上下文。
在创建按钮时,在文档上而不是在html中注册onClick事件。
$(document).on('click', 'button.btn-inverse', function() { toggleVisibility(this); return false;});
不要创建内联HTML字符串,不要使用侵入式Javascript。
虽然我甚至不建议您使用vanilla jQuery创建它们,但您可以尝试:
var $button = $('<button></button>', {
'text' : word
'type' : 'button',
'class' : 'btn btn-block btn-inverse active',
'data-toggle' : 'button tooltip',
...
// any other attributes
});
// append the $button anywere
$( someContainer ).append($button);
$( someContainer ).on('click', '.btn', function(event){
// you can refer to the button with $(this) here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.