Jquery, get url from click and pass to confirm but

2019-07-30 19:10发布

问题:

I have this jquery code:

$("#deletec-box").dialog({
     autoOpen: false,
     resizable: false,
     height:230,
     modal: true,
     buttons: {
      "Confirm": function() {
          window.location = 'hrefurlfromclick';
          $(this).dialog("close");
      },
      Cancel: function() {
          $(this).dialog("close");
      }
     }
    });

    $("#deletec-confirm").click(function() {
        $("#deletec-box").dialog("open");
        return false;
    });

Then in the page I have a link that calls the dialog:

<a href="?action=delc&cid=2" id="deletec-confirm">Delete</a>

My question is how do I get the value of href so if the person does confirm it loads the link they originally clicked?

回答1:

You can get the href attribute with: $('#deletec-confirm').attr('href');

Your code now looks like:

$("#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;
});


回答2:

Do you have to use the jQuery UI dialog? You could instead use the confirm box, like this:

$("#deletec-confirm").click(function(event) {

    if(!confirm("Are you sure you want to delete this item?")) {
        event.preventDefault();
    }

});

This way, if the cancel button is hit the links original action is prevented, otherwise the links is free to perform it's original action.

Here's a quick example.



回答3:

Get it with attr

var url = $('#deletec-confirm').attr('href');
$("#deletec-box").dialog({
 autoOpen: false,
 resizable: false,
 height:230,
 modal: true,
 buttons: {
  "Confirm": function() {
      window.location = url;
      $(this).dialog("close");
  },
  Cancel: function() {
      $(this).dialog("close");
  }
 }
});