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

十年热恋 提交于 2019-12-25 04:17:24

问题


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.



来源:https://stackoverflow.com/questions/12012492/jquery-returns-b-fn-b-init102

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!