Jquery, get dynamic attribute for dialog box
This is an extension to a previous question which was answered. But have a different need/issue. Here is the jquery code:
$("#deletec-box").dialog({
autoOpen: false,
resizable: false,
height:230,
modal: true,
buttons: {
"Confirm": function() {
window.location = $('#deletec-confirm').attr('href');
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
$("#deletec-confirm").click(function() {
$("#deletec-box").dialog("open");
return false;
});
Here is the original link:
<a href="?action=delc&cid=2" id="deletec-confirm">Delete</a>
But I have multiple links on one page with the same id. So I changed the link to:
<a href="?action=delc&cid=2" id="deletec-confirm10">Delete</a>
<a href="?action=delc&cid=2" id="deletec-confirm9">Delete</a>
<a href="?action=delc&cid=2" id="deletec-confirm12">Delete</a>
How would I dynamically get the link the person clicked on to get the dialog? Right now it gets the url like so:
window.location = $('#deletec-confirm').attr('href');
Do I change the id to a class in the link? Or is there another way to dynamically select the id of the link so I can keep the id= attribute for each link?
Side note, if this i开发者_运维技巧s considered duplicate please let me know what I need to do.
I recommend you to use a common class
to all your links. like this:
<div id="deletec-box">Are you sure you want to delete?</div>
<a href="?action=delc&cid=2" class="deletec-confirm">Delete</a>
<a href="?action=delc&cid=2" class="deletec-confirm">Delete</a>
<a href="?action=delc&cid=2" class="deletec-confirm">Delete</a>
Then, you could store the 'clicked link' with .data()
$("#deletec-box").dialog({
...
buttons: {
"Confirm": function(idx) {
window.location = $('#deletec-box').data('openerLink').attr('href');
$(this).dialog("close");
},
...
}
});
//By binding with a class, you bind once for all
$(".deletec-confirm").click(function() {
$("#deletec-box").data("openerLink", $(this)); //Store the link in the dialog
$("#deletec-box").dialog("open");
return true;
});
The advantage of using .data()
is that you don't use global vars, and store what you want only where you want.
Hope this helps.
If you want to adhere to HTML/XHTML standards you'll need to adjust the id
attributes so they are unique, or remove them and use a class for your selectors instead as I have done in the example below.
Here's a basic approach that will alert the href
attribute values, adjust as necessary:
var $sender;
$("#deletec-box").dialog({
...
buttons: {
"Confirm": function(idx) {
alert($sender.attr('href'));
$(this).dialog("close");
},
...
}
});
$(".deletec-confirm").click(function() {
$sender = $(this);
$("#deletec-box").dialog("open");
return true;
});
Combined with this HTML as an example:
<div id="deletec-box">Are you sure you want to delete?</div>
<a href="#1" class="deletec-confirm">Delete</a>
<a href="#2" class="deletec-confirm">Delete</a>
精彩评论