我必须编写一个函数来创建a标签的 HTML 代码,这个函数还将一个函数处理程序传递给onclick创建的a标签事件。代码:
function a(text,functionHandler){
return '<a href="#" onclick="'+functionHandler+'">'+text+'</a>';
}
//usage
var a1 = a('link',function(){
alert('test');
});
Run Code Online (Sandbox Code Playgroud)
将函数传递给字符串不起作用。所以我的问题是:how to pass a function handle to onclick event and get a HTML code of created a tag?
您目前的方法有几个问题 -
function是关键字。您不能将其用作参数。与其将锚作为字符串返回,不如将其作为元素返回 -
function createAnchor(text, clickHandler) {
var link = document.createElement('a'); // creates an anchor element
link.href = "#"; // sets the href
link.onclick = clickHandler; // sets the click handler
link.innerHTML = text; // assigns the inner html string
return link; // now return it
}
Run Code Online (Sandbox Code Playgroud)
进而 -
var myAnchor = createAnchor('link', function () {
alert('test');
});
// Add this element wherever you want
Run Code Online (Sandbox Code Playgroud)
请参阅有关createElement和element的文档。
编辑
如果要将此锚元素作为子元素添加到现有 DOM 元素,请使用appendChild -
var myAnchor = createAnchor('link', function () {
alert('test');
});
document.getElementById('x').appendChild(myAnchor);
Run Code Online (Sandbox Code Playgroud)
编辑 2
如果你真的想要你的锚字符串,那么使用上面的函数创建锚元素,将它作为子元素附加到你想要的元素,然后innerHTML在父元素上使用。该方法在这里演示 -
function createAnchorString(parentId, text, clickHandler) {
var link,
parent;
link = createAnchor(text, clickHandler); // call the previous function
parent = document.getElementById(parentId);
parent.appendChild(link);
return parent.innerHTML;
}
var myAnchorString = createAnchorString('x', 'link', function () {
alert('test');
});
alert(myAnchorString);
Run Code Online (Sandbox Code Playgroud)
function a(text,function){
return '<a href="#" onclick="myfunction();">'+text+'</a>';
}
function myfunction() {
alert('test');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6400 次 |
| 最近记录: |