开发者

jQuery add attr to end of string

I want to add the attribute href to the end of an url:

This should be pretty easy. This is what I have, but I think something's wrong.

$('开发者_StackOverflow.delete-code').click(function() {
    var row = $(this).parent().parent();
    $.ajax({
        type: "POST",
        url: "http://website.com/admin/home/deleteCode/"+$(this).attr('href'),
        data: $(this).attr('href'),
        success: function() {
            $(row).hide();
        }
    });
    return false;
});

This works when I hard-code in the href


Your code should work. The problem is the url. Some browsers need to get 200 OK to call the success callback.

Try changing:

url: "http://website.com/admin/home/deleteCode/"+$(this).attr('href'), 

to:

url: "http://www.flickr.com/search/?q="+$(this).attr('href'),

It should work.

Also you may want to change some little things:

  1. The data property is redundant and don't work with pretty urls out of the box.
  2. jQuery has a $.get method to make GET requests.
  3. closest('tr') rather than parent().parent() will make your code more readable.
  4. href is an element attribute, so it can be accessed directly trough DOM

So maybe this can be a better option depending on what you need:

$('.delete-code').click(function() {
    var tr= $(this).closest('tr')
    $.get("http://www.flickr.com/search/?q=" + this.href, 
       function(){
          tr.hide()
       })
    return false
})

Good luck.


there's nothing wrong with your code, it's probably just your DOM traversal or the way you're doing your AJAX.

and Julio Protzek is right, unless you're using an error function or want to make a synchronous XMLHttpRequest (a fairly rare case), you could just as easily say

$('.delete-code').click(function() {
    var row = $(this).parent().parent();
    $.get(
        "http://website.com/admin/home/deleteCode/"+$(this).attr('href'),
        {}, // or { data: $(this).attr('href') }, if you needed to send that
        success: function() {
            $(row).hide();
        }
    });
    return false;
});

and remember, unless .delete-code applies to an <a class="delete-code"> element, it's a different element you're trying to get the .attr('href') from.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜