Domanda

i'm trying to obtain the src of an image placed before the link i click:

<ul id="grid">
        <li><a href="prod-det.php" class="tip" rel="product-tip.php"><img src="../upload/mainmenu-articolo-ico.jpg" width="110" height="115"><p>GSE29KGYCSS / GSE29KGYCWW</p></a>
        <div class="options">
            <a href="#briciole" class="opt-compare off">Compare</a>
            <a href="#briciole" class="opt-wish off">Wishlist</a>
        </div></li>

and write this path:

$('.options a').click(function() {
 $("#compare .myge-grid").append(closest('img').attr('src'));

but i fail to obtain the img src. Someone can please point me to the right direction? tks in advance

edit: more code here http://jsfiddle.net/X2NBn/1/

È stato utile?

Soluzione

Update:
According to your document structure, this is what you're looking for:

$("img", $(this).parents('li:first')).attr("src");

Note: attr("src") returns the src as defined in the HTML source ('../upload.png'). If you want the full path, use .prop("src") instead.


Old answer
You should define the JQuery object on which you want to use the .closest() method.

Currently, you're not using the jQuery .closest method, but a (probably undefined) closest() function.

This should work as intended, after adding $(this):

$('.options a').click(function() {
    $("#compare .myge-grid").append($(this).closest('img').attr('src'));

Altri suggerimenti

closest is not magic. It doesn't mean "visually closest". It means "nearest ancestor". Rather than searching for the list item every time the element is clicked, as in Rob W's answer, you'd do better to iterate over the list items, and bind the click handler to each in turn, like this:

$('#grid li').each(function() {
    var item = $(this);
    item.find('.options a').click(function() {
        $("#compare .myge-grid").append(item.find('img').attr('src'));
    });
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top