Domanda

When i click on a link "zmeniť pozíciu", i want to save its closest img to variable.

<table border="1">
    <tbody> 
        <tr>        
            <th rowspan="3">1</th>
            <th>Nadpis</th>
            <td colspan="9">Eiusmod tempor</td>
            <td> <a href="#">zmeniť</a> </td>
            <td rowspan="3"> <a class="zmenit-poziciu" href="#">zmeniť pozíciu</a> </td>
        </tr>
        <tr>
            <th>Text</th>
            <td colspan="9">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam ...
            </td>
            <td> <a href="#">zmeniť</a> </td>
        </tr>
        <tr class="obrazok">
            <th>Obrázok</th>
            <td colspan="9"> <img alt="img" src="http://lorempixel.com/500/120/sports/1"> </td>
            <td ><a href="#">zmeniť</a></td>

        </tr>

    </tbody>
</table>

i tried this but it doesn't work

$(".zmenit-poziciu").click(function() {

        var img = $(this).parent().closest("obrazok").html();
        alert(img);
        return false
    });

demo

È stato utile?

Soluzione

You can get the image like this

$(".zmenit-poziciu").click(function () {
  var img = $(this)
            .closest('tr') // get to the tr level
            .nextAll(".obrazok:first") // find the next tr sibling with class=obrazok
            .find('img'); // find the img
  alert(img.attr('src'));
  return false;
});

http://jsfiddle.net/wirey00/Z5CeE/

Altri suggerimenti

Wrong selector used.

Change:-

var img = $(this).parent().closest("obrazok").html();

To:-

var img = $(this).parent().closest(".obrazok").html();

Using your current selector, you are actually looking for a tag called obrazok, which I'm guessing you don't have in your doc.

Closest gets you the closest element matching the selector higher up the hierarchy. Docs

From the docs:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

In your case, the tr matching .obrazok is not higher in the hierarchy when viewed from the clicked link.

You will need something that traverses the DOM and gets you the nearest element in the DOM. This answer I posted for another question I believe should help: https://stackoverflow.com/a/12873187/921204

You can use it like:

$(".zmenit-poziciu").click(function() {
    var img = nextInDOM('.obrazok', $(this));
    alert(img);
    return false
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top