Reputation: 2923
I have a series of click events that I want to grab the text of their respective sibling.
In this case I am setting id
to the output of $(this).siblings('div').children('p.item_name').text()
, which is different for every item.
Is there a way to globally set $(this).siblings('div').children('p.item_name').text()
so that I can just assign id
to the same variable?
$('.buy').click(function(e){
e.preventDefault();
var id = $(this).siblings('div').children('p.item_name').text();
shoppingClickHandler('buyItem', id);
})
$('.try').click(function(e){
e.preventDefault();
var id = $(this).siblings('div').children('p.item_name').text();
shoppingClickHandler('tryItem', id);
})
$('.suggest').click(function(e){
e.preventDefault();
var id = $(this).siblings('div').children('p.item_name').text();
shoppingClickHandler('suggestItem', id);
})
Upvotes: 0
Views: 69
Reputation: 229633
You can wrap the shoppingClickHandler
call in a function that does the id lookup internally:
function dynamicShoppingClickHandler(action, node) {
var id = $(node).siblings('div').children('p.item_name').text();
shoppingClickHandler(action, id);
}
$('.buy').click(function(e){
e.preventDefault();
dynamicShoppingClickHandler('buyItem', this);
})
$('.try').click(function(e){
e.preventDefault();
dynamicShoppingClickHandler('tryItem', this);
})
Upvotes: 1
Reputation: 59283
Try a function:
function getId(item) {
return $(item).siblings('div').children('p.item_name').text();
}
Then you could just do, for example,
$('.buy').click(function(e){
e.preventDefault();
// Old Version:
// var id = $(this).siblings('div').children('p.item_name').text();
// New Version:
var id = getId(this);
shoppingClickHandler('buyItem', id);
})
Upvotes: 3