How can I capture an element with jQuery without being able to reference it using a class, ID, etc.

I have a table like:

<table> <thead> <tr> <th>Hostname</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>127.0.0.1</td> <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td> </tr> <tr> <td>127.0.0.2</td> <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td> </tr> <tr> <td>127.0.0.3</td> <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td> </tr> </tbody> 

What I'm trying to do is when the user clicks Delete , that the link is replaced with one of these downloadable images, so the user cannot click the link repeatedly.

How do I get the element a , so to speak, so I can set the HTML accordingly using jQuery?

In other parts of the site, I can connect rel="host-1" (or the like) to the link, so I can easily link to it to change the HTML.

+6
source share
5 answers

You can use the attribute selector to select based on the name <a/>

Alternatively, you can use one() so that the handler fires only once.

 $("a[name='delete']").one("click", function(){ $(this).html("Doing something...") }); 

Jsfiddle example

note, just replacing .html() will not remove the embedded js, you can use .replaceWith() to completely remove <a/>

 $("a[name='delete']").one("click", function() { $(this).replaceWith($("<img/>").attr({src: "http://placekitten.com/g/50/50"})) }); 

Jsfiddle example

+7
source
 $('a[name="delete"]').click(function() { }); 

EDIT

Do not use embedded JS. writing the following is much cleaner.

 $('a[name="delete"]').click(function() { var thehost = $(this).parent().prev().html(); remove_host(thehost); }); 
+4
source

You can pass this in a remove_host call, for example:

 remove_host('127.0.0.1', this); 

This will give you a link to a DOM element that you can wrap in jQuery.

+2
source

I'm not sure if you can change the markup or not, but here is one option.

 <tr> <td>120.0.0.2</td> <td><a name="delete" data-ip="120.0.0.2">Remove</a></td> </tr> $("a[name=delete]").one("click", function(e) { e.preventDefault(); $("<span>Loading</span>").insertBefore(this); var ip = $(this).hide().data("ip"); remove_host(ip); }); 
0
source

if using jQuery ...

 <script type=text/javascript> $("document").ready( function(){ $("a[name=delete]").click(function(){ $(this).hide().after('<img src="loading.png" />'); }); }); </script> 
0
source

Source: https://habr.com/ru/post/888253/


All Articles