简体   繁体   中英

How to pass `this` as an argument in javascript function?

I am using javascript in my project.

I have on HTML table <table id='idDocList'> and I am doing append some html on this table as below code. But I want to hide respective <tr> when user click on Delete anchor tag.

$("#idDocList").append("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a onclick=deleteDocument(this,'" + file.name + "')> Delete</a></td></tr>");

How can i do this using Jquery?

The following example does not work

function deleteDocument(CurAnchorTag, fileName) {
    $(CurAnchorTag).closest('tr').hide();
}

I don't want to use ID for <a> tag as I have many Documents.

As a quick fix, you can use like this,

$(CurAnchorTag).closest('tr').hide();

Replaced <tr> with tr

You can remove the inline function call with jquery like this way,

$("#idDocList").on("click", "td a", function() {
    $(this).closest("tr").hide();
    var filename = $(this).closest("td").prev().text();
});

I would suggest you to change your code to:

var newRow = $("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a href='#'> Delete</a></td></tr>").appendTo("#idDocList");
newRow.find( 'a' ).click( function( e ) {
    e.preventDefault();
    $( this ).closest('<tr>').hide();
});

you can just use

$(".delete_link").click(function(){$(this).closest('tr').hide();}

Jquery will use the this of which ever element called it. There will be no need for the onclick on the html file.

You would better use event delegation and get rid of inline onclick handlers all together:

$('#idDocList').on('click', '.btn-delete', function() {
    $(this).closest('tr').hide();
    // read filename: $(this).data('filename')
});

And use it with HTML (the sting you append):

"<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a class="btn-delete" data-filename='" + file.name + "'>Delete</a></td></tr>"

Note the part:

<a class="btn-delete" data-filename="filename">Delete</a>

You recommend you to use event for a class using the jquery

$("#idDocList").append("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a class='delete_link'> Delete</a></td></tr>");

The code below will add the event and need to execute always after add a "tr", unless you use a delegate to this

$(".delete_link").click(function(){ $(this).closest("tr").hide() });

If you don't want to use a class you can use this

$("#idDocList td > a").click(function(){ $(this).closest("tr").hide() });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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