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 ca开发者_运维知识库n 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
Try changing:
typeElem.setAttribute('onclick',"delete(position)");
to
typeElem.setAttribute('onclick',"delete(" + position + ")");
IE handles setAttribute
differently to other browsers, particularly event handlers attributes. 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. Also, avoid using functions named after operators in JavaScript. Specifically in this case I'd rename the delete()
function.
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);
}
精彩评论