[英]how to pass object in inline onclick event in dynamically creating elements
[英]how to pass element in inline onclick event in a dynamically created string
我有一个功能,可以根据收到的参数为Kendo Grid Toolbar创建一个按钮模板。 我想要做的是通过onclick函数传递名为element
(它是一个jquery元素)的参数内的属性之一,以便我可以在函数fnAdd(element)
访问该元素。
function(parameter)
{
var template="<button onclick='fnAdd("+param.element+")'>Add</button>";
$('#grid').kendoGrid({
toolbar: template
});
}
当前,onclick功能不起作用。 我尝试在参数上使用JSON.stringify并将其通过onclick传递并能够在fnAdd()上获取它,但我根本无法访问param.element。
有人知道如何解决吗?
您可以使用bind
方法附加params
来实现此目的。 下面的示例代码
function add(param) { let btn = document.createElement('button'); btn.innerHTML = 'NEW - ' + new Date().getTime(); btn.onclick = newButtonOnclick.bind(this, (param || new Date().getTime())) document.body.append(btn) } function newButtonOnclick(param) { alert(param); }
button { display: block; margin-bottom: 1em; }
<button type="button" onclick="add();"> Add New Button </button>
我希望此解决方案可以为您提供帮助:
记住Patter designs
,在这种情况下,我们可以使用Factory patter
,您可以重用此代码来创建代码块。
在此示例中,每个按钮还可以触发不同的功能,并且可以具有不同的参数!
// YOUR JAVASCRIPT WITH ACCESS TO THE DOM
// here you call your plugin where the DOM is not present
function getButton() {
let newButtonInString = createButtonPlugin();
// in newButton you just have the string
// now convert it to html using Jquery
let htmlButton = $(newButtonInString);
document.body.append(htmlButton[0]);
}
// YOUR PLUGIN JS
let counter = 1;
function createButtonPlugin() {
// you can take this params from the UI
let paramsExample = {
text: `New Button ${counter}`,
functionParams: {
counter: counter
} // Could be an object or what you want!
}
let bp = new ButtonPrototype(paramsExample);
let newButton = bp.createButton();
counter++;
// return string to the place where you can render the button
return newButton;
}
class ButtonPrototype {
constructor(params){
this.params = params
}
createButton() {
return `<button onclick=fn(${JSON.stringify(this.params.functionParams)})>${this.params.text}</button>`
}
}
function fn (args) {
alert(`Success ${args.counter}`)
}
您的html:
<button onclick="getButton()">add</button>
我还留下了代码库:刚刚用您的新评论更新了! https://codepen.io/ruben-saucedo/pen/GbxXNG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.