简体   繁体   中英

extract value of href a tag using jquery

<tr class="field_20 field_facebook">
<td class="label">Facebook</td>
<td class="data"><p><a href="http://facebook.com/facebook">Test</a></p>
</td></tr>
<img id="fb" src="fb.png">

Hello, so this is what I have and I want to select using jquery the value http://facebook.com/facebook and open the link. this is what I have so far:

<script>
jQuery(document).ready(function(){
jQuery("#fb").click(function() {
  var fb = jQuery(".field_20 field_facebook").find("a").attr("href");
window.open(fb);

}); //click function ends
}); // document ready ends
</script>

any help would be greatly appreciated thank you.

Use .field_20.field_facebook (no space, but a period).

The class attribute allows you to define multiple classes on the same element with a space. This is distinct from jQuery (and CSS) selectors where the space is a descendant selector. That is, .field_20 field_facebook tries to select a <field_facebook> element that is a descendant of an element with the .field_20 class. Using .field_20 .field_facebook would not work either because the descendant selector is still there. Omitting the space is proper syntax for selecting via multiple classes on the same element.

Try this as your jQuery script:

$(document).ready(function() {

    $("#fb").click(function() {
        var fb = $('td.data a').attr('href');
        alert(fb);
        window.open(fb);
    }); //click function ends

}); //END $(document).ready()

Your selector line can be simplified to:

var fb = jQuery(".field_20.field_facebook a").attr("href");

Just like in CSS, you can select the a which is a child of an element with class .field_20.field_facebook .

<tr class="field_20 field_facebook">

The classes are available on the same element.

So there should be no space between the 2 classes when used in the selector.

jQuery(".field_20.field_facebook")

Use the line below to access the facebook link

jQuery(".field_20.field_facebook a").attr("href");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM