Reputation: 671
Basically, I have some buttons
<div class="button">
<!--Some other stuff-->
<div class="id">HD5sjW</div>
</div>
<div class="button">
<!--Some other stuff-->
<div class="id">yqWH3X</div>
</div>
<div class="button">
<!--Some other stuff-->
<div class="id">KWZy5V</div>
</div>
and I wanted to use JavaScript to link to another page and I couldn't find an explanation so this is what I came up with and obviously doesn't work at all - how am I meant to do this?
$('.button').click(function () {
confirm("http://domain.com/thing?id=" + $(this + " .id").text());
});
The confirm is just for a blatant output
As another thing, how should I structure my questions better and type of title?
Upvotes: 0
Views: 47
Reputation: 19571
Here's a solution using .click()
using .hover()
will cause the confirm box to trigger multiple times.
$('.button').click(function () {
//find out which buttton this is
var currentBtn = $('.button').index( $(this) );
//use currentBtn to find its matching id div using `:eq()`
var currentId = $('.id:eq('+currentBtn+')').text();
confirm("http://domain.com/thing?id=" + currentId)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="button">
<!--Some other stuff-->
<div class="id">HD5sjW</div>
</div>
<br>
<div class="button">
<!--Some other stuff-->
<div class="id">yqWH3X</div>
</div>
<br>
<div class="button">
<!--Some other stuff-->
<div class="id">KWZy5V</div>
</div>
Upvotes: 1
Reputation: 97672
You can use .find()
or a context parameter in the jQuery function.
$('.button').hover(function () {
confirm("http://domain.com/thing?id=" + $(".id", this).text());
});
$('.button').hover(function () {
confirm("http://domain.com/thing?id=" + $(this).find('.id').text());
});
Upvotes: 1