简体   繁体   English

javascript:锚标签问题

[英]javascript:anchor tag problem

function main(){

var delImage=document.createElement("img"); 
delImage.setAttribute("alt","Edit"); 
delImage.setAttribute("src","drop.png");

var position=newRow.rowIndex;
var typeElem=document.createElement("a");
typeElem.setAttribute("name","delete");  
typeElem.setAttribute("href","#");
typeElem.appendChild(delImage);
typeElem.setAttribute('onclick',"delete(position)");

newRow.insertCell(lastCell).appendChild(typeElem);

}

function delete(pos){
alert(pos);
}

i am not able to call the delete function when anchor tag was clicked...what can i want to change to achieve this? 单击锚标记时,我无法调用删除功能...我要更改些什么才能实现此目的?

Try 尝试

typeElem.onclick = function(){
    delete(position);
};

and better use a more meaningful name like deletePosition or something like that 最好使用更有意义的名称,例如deletePosition或类似的名称

Try changing: 尝试更改:

typeElem.setAttribute('onclick',"delete(position)");

to

typeElem.setAttribute('onclick',"delete(" + position + ")");

IE handles setAttribute differently to other browsers, particularly event handlers attributes. IE处理setAttribute方式与其他浏览器不同,尤其是事件处理程序的属性。 For this reason and for the sake of neater code it's much easier to avoid using setAttribute where DOM properties already exist, which generally work uniformly across browsers. 因此,为了使代码更整洁,避免在已经存在DOM属性的地方使用setAttribute更加容易,该属性通常在浏览器之间是一致的。 Also, avoid using functions named after operators in JavaScript. 另外,请避免在JavaScript中使用以运算符命名的函数。 Specifically in this case I'd rename the delete() function. 特别是在这种情况下,我将重命名为delete()函数。

function main() {
    var delImage = document.createElement("img");
    delImage.alt = "Edit";
    delImage.src = "drop.png";

    var position = newRow.rowIndex;
    var typeElem = document.createElement("a");
    typeElem.name = "delete";
    typeElem.href = "#";
    typeElem.appendChild(delImage);
    typeElem.onclick = function() {
        doDelete(position);
    };
    newRow.insertCell(lastCell).appendChild(typeElem);
    typeElem = null;
}

function doDelete(pos){
    alert(pos);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM