如何使用jQuery获取click href值?

时间:2011-06-05 00:02:27

标签: jquery

假设我有一个这样的锚:

<a onClick="return confirm('Sure?')" href="http://stackoverflow.com/">Click here</a>

当我点击“点击这里”时,我是否可以获得href“http://stackoverflow.com/”的价值?请记住,我没有其他属性可以提供帮助,例如id或name!

我正在覆盖确认功能,我需要将用户重定向到锚点中提供的位置,如果他们点击确定如下:

window.confirm = function(msg) {
      var targetUrl = jQuery(this).attr("href");
      jQuery("#alert_box").dialog({
         autoOpen: false,
         show: "slide",
         modal: true,
         width: 400,
         resizable:false,
         title: '<img src="icons/confirm.png" /> Confirm!',
         buttons: { "Cancel": function() { 
                        jQuery(this).dialog("close");                       
                    },
                 "OK": function() { 
                        //jQuery(this).dialog("close");
                        jQuery(location).attr('href', targetUrl);
                    }
                   }
      });

      jQuery("#alert_box").html(msg);
      jQuery("#alert_box").dialog("open");
      return false;
  }

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

要重定向用户,请使用:

window.location.href = targetUrl;

而不是:

jQuery(location).attr('href', targetUrl);

最好删除内联JavaScript,例如:

<a class="confirm" href="http://www.example.com">..</a>

// script.js
$('a.confirm').click(function(e) {
    e.preventDefault();
    if (confirm('Are you sure?')) {
        window.location.href = $(this).attr('href');
    }
});

您的确认函数声明中的this也不会引用<a>元素。你可能想要使用类似的东西:

<a onclick="return confirm(this, 'Sure?')" href="...">...</a>

// script.js
function confirm(e, msg) {
    var targetUrl = $(e).href('attr');
    // ...
}
相关问题