我的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 () {});
中一样。