Jquery returns b.fn.b.init[102]

2019-08-25 04:18发布

问题:

I have to select multiple elements, all them have the class ="org-box". Inside that box there is a link a that I want to capture the href. So I do this

$("a.org-box").click(function (e) {
 e.preventDefault();
 var link = $(e).html();
 $('.col-right').prepend("<b>" + link +"</b>");
})

What I always get is null, and I have tried other selectors like
var link = $(e.a).attr("href").html();

With the same luck.

I checked what I get from that selection $("a.org-box") and I get this -> b.fn.b.init[102]

If I do this $("a.org-box:first").attr("href"); I get correctly the href, but when I do $("a.org-box").attr("href"); I just get the first one.

What Im doing bad ?? How to select all the a.org-box and capture href on click ?

回答1:

<a href="http://google.com" class="org-box">Click to prepend Google</a>

--

$("a.org-box").on('click', function(e) {
    e.preventDefault();
    $('.col-right').prepend("<b>" + e.target.href +"</b>"); //http://google.com
});

FIDDLE



回答2:

You could use:

$("a.org-box").click(function (e) {
    $('.col-right').prepend('<b>' + $(this).attr('href') + '<b>');
    e.preventDefault();
});

this is set to e.target, with e.target being the target of the event (the item that was clicked on). You can use $(this).attr('href'), $(this).prop('href'), this.href, or any of the same variants using e.target.

I can't tell is whether you need the inner text (.text()) of the link, or the href attribute, so I'm assuming the latter.



回答3:

jQuery selectors return ALL matched elements, so what's happening is you're getting the jQuery collection of those elements back from the selector, the event data is NOT the element that triggered the event a correct implementation would be:

$(a.org-box).click(function(){
    var link = $(this).html();
    $('.col-right').prepend("<b>" + link +"</b>");
});

you use $(this) because jQuery is iterating over the collection so just like if you were using .each() the this object holds your element.