开发者

How do you find which link was clicked?

How do I get a reference to the clicked link to delete the correct row?

<tr>
<td>c1r1</td>
<td>c2r1<开发者_StackOverflow中文版/td>
<td><a href="javascript:delete_row();">delete</a></td>
</tr>

<tr>
<td>c1r2</td>
<td>c2r2</td>
<td><a href="javascript:delete_row();">delete</a></td>
</tr>

function delete_row() {
    this.parent().parent().remove();
}

I know I can use (in jquery)

$('a').click(function() {
    this.parent().parent().remove();
}

Or even this

$('a').live('click', function() {
    this.parent().parent().remove();
});

To bind the function to dynamically created links.

But I'm looking for the way to get a reference to the clicked link without jquery. I'm using jquery inside the function, but that is not the point.

Edit Many are suggesting to use this in the function as parameter, I have tried that, but it returns window:

<a href="javascript:delete_row(this);">delete</a>

function delete_row(elem) {
    console.log(elem);
}

Firebug console: Window config_maker.php


Contrary to all the other answers, you cannot pass this in this case, because that would be referring to the window object and not the link. Why? Because you are not using an event handler. You are using the javascript: protocol. Don't use that to invoke your functions, but use an event handler instead. Change your links to this and you'll be straight...

<a href="javascript:void(0);" onclick="delete_row(this);">delete</a>

This is still far from ideal, as unobtrusive Javascript is the way to go these days. But this will at least get your code working.


You can pass the reference using this.

<a href="javascript:delete_row(this);">


<tr id='row1'><td><a rel="row1" href="javascript:delete_row('row1');">delete</a></td></tr>

<tr id='row2'><td><a rel="row2" href="javascript:delete_row(this.rel);">delete</a></td></tr>

...

function delete_row(varID) {
document.getElementById(varID).remove();

}

or

function delete_row(varID) {
$('#'+varID).remove();

}


this might help You

document.addEventListener("click", listener);
function listener(event){
     if(event.target.nodeType != 'a') return false;
     document.remove(event.target.parentNode.parentNode);
}


Use this

<a href="javascript:delete_row(this);">


Can't you just use this as parameter of the function?

<a href="javascript:delete_row(this);">xxx</a>

And in Javascript:

function delete_row(clickedLink) {
    ...
}


Use...

function delete_row(link) {
    link.parent().parent().remove();
}

Then call javascript:delete_row(this);


just check this object inside handler function

use : this.id

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜