2

我正在使用 javascript 创建 html 页面,但无法在单击按钮时调用某些函数。

var alernative = "plot1";
var buttonvalue= "mybutton";
 function callme()
 {alert("hello");}   

 $('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' +   callme() + '";></div>');

在上面的代码中,创建一个按钮并赋予其值并调用按钮的 onclick 函数,但是当页面加载时它显示警报(不应该发生)并且它没有在按钮单击时发出警报。

希望得到建议或帮助。

4

2 回答 2

6

您需要将函数名称作为字符串的一部分传递:

$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');
于 2013-05-30T14:10:15.997 回答
0

用字符串编写 HTML 是一种不好的做法,DOM 的存在是有原因的!

var input = $('<input/>', {
    type: "button",
    style: "float: right",
    value: buttonValue
}),
    element = $('<div/>').append(input);
input.click(function () {
    callme();
});
$('#test').html(element);
于 2013-05-30T14:17:07.520 回答