0

我正在尝试创建一个按钮,以便在将某些内容上传到数据库之前添加视图。

我在我的网站上使用 jquery,所以如果解决方案是在 jquery 中,那就更好了。

现在我正在尝试我在这里找到的一段代码:Creating Dynamic button with click event in javascript

这就是我适应我的情况的方式:

var element = document.createElement("input");
//Assign different attributes to the element. 
element.type = 'button';
element.value = 'hello'; // Really? You want the default value to be the type string?
element.name = 'HELLO';  // And the name too?
element.onclick = window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');;

var foo = document.getElementById("registerButtonDiv");
//Append the element in page (in span).  
foo.appendChild(element);

它添加了按钮(嗯,它是一个简单的按钮,不像我网页中的其他按钮,我猜是与 css 相关的东西)

但是,如果我尝试使用类似 onclick 事件的方法,它会创建按钮但不添加 onclick 部分。我尝试更改引号,而不是使用它们……很多事情,所以现在可能是错误的。不要那么认真,我只是复制最新版本。使用示例中的警报,它可以正常工作。

我该怎么做才能解决这个问题?

我需要这样做,因为我必须将一些实际填充的变量传递到另一个页面,这是我找到的最简单的解决方案。

4

2 回答 2

1

由于onclick是一个事件,它需要一个处理程序。在这里,您可以使用任何可以满足您要求的处理程序来处理事件。

element.onclick = function(){
    window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');
};

演示

于 2013-11-14T17:04:30.120 回答
1

您需要将函数引用传递给 onclick:

element.onclick = function(){
    window.open(...);
};

或使用 jquery:

var element = $('<input type="button" value="hello" name="HELLO">');
element.on('click', function() {
    window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');
});
$("#registerButtonDiv").append(element);

jsfiddle

于 2013-11-14T17:12:27.857 回答