我想传递一个参数(即字符串)到Onclick函数。
目前,我是这样做的:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
例如,result.name = string "Add"。
当我点击这个按钮时,我有一个错误,说“Add is not defined”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
我想传递一个参数(即字符串)到Onclick函数。
目前,我是这样做的:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
例如,result.name = string "Add"。
当我点击这个按钮时,我有一个错误,说“Add is not defined”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
当前回答
你可以在你的onclick方法中使用这段代码:
<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>
其他回答
您可以传递一个引用或字符串值。只需将函数放在双逗号“”中,如下所示:
如果要求在HTML代码中引用全局对象(JavaScript),您可以尝试这样做。[不要在变量周围使用任何引号('或")]
小提琴参考。
JavaScript:
var result = {name: 'hello'};
function gotoNode(name) {
alert(name);
}
HTML:
<input value="Hello" type="button" onClick="gotoNode(result.name)" />
下面是我正在使用的jQuery解决方案。
jQuery
$("#slideshow button").click(function(){
var val = $(this).val();
console.log(val);
});
HTML
<div id="slideshow">
<img src="image1.jpg">
<button class="left" value="back">❮</button>
<button class="right" value="next">❯</button>
</div>
这是一种发送值或对象的好方法。
<!DOCTYPE html>
<html>
<body>
<h1 onclick="test('wow',this)">Click on this text!</h1>
<script>
var test = function(value,object) {
object.innerHTML= value;
};
</script>
</body>
</html>
如果用于生成一组具有不同处理程序参数的按钮。
JavaScript闭包
let some_button = document.createElement( "button" );
some_button.type = "button";
some_button.onclick = doWithParam( some_param );
function doWithParam( param ){
return function(){
alert( param ); // <-- Your code here
}
}
如果我们这样做:
some_button.onclick = foo( some_param );
function foo( param ){
alert( param );
}
然后函数foo在每个更新页面之后启动。
如果我们这样做:
for( let i = 0; i < 10; ++i ){
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
document.body.appendChild(inputElement);
}
然后,对于循环中创建的所有按钮,参数的最后一个值是“result.name”。