开发者

Converting string to onclick handler in javascript

I have a varia开发者_开发知识库ble ElementAction which is a string javascript:deleteRow();. How do I assign the literal content of ElementAction to an onclick handler of another HTML element. HTMLElement.onclick = ElementAction doesn't work.

Thanks for any help.


Get rid of that "javascript:" prefix first; it's useless. You can create a function instance from your string with:

var handler = new Function("event", ElementAction.replace(/^javascript:/, ''));

Then you can attach the handler either by setting the "onclick" attribute directly or by using one of the APIs as in JCOC611's answer.


You can:

element.onclick = deleteRow;

Or even more compatible:

if(element.attachEvent){
   element.attachEvent("onclick", deleteRow);
}else{
   element.addEventListener("click", deleteRow, false);
}

Running a string is not recommended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜