开发者

How do I grab an element with jQuery without a way to reference it via class, ID, etc

开发者 https://www.devze.com 2023-03-06 02:46 出处:网络
I have a table like so: <table> <thead> <tr> <th>Hostname</th> <th>Action</th>

I have a table like so:

<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 a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a开发者_JAVA百科 element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.


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

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

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

Example on jsfiddle

side note, just replacing with.html() will not remove the inline js, you could use .replaceWith() to completely remove the <a/>

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

Example on jsfiddle


$('a[name="delete"]').click(function() {

});

EDIT

Don't use inline JS. writing the following is much cleaner.

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


You could pass this in the call to remove_host, like this:

remove_host('127.0.0.1', this);

This will give you a reference to the DOM element, which you can wrap in jQuery.


I am not sure whether you are able to change the markup or not, but here's 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);
});


if using jQuery...

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

精彩评论

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