我试图劫持button
元素,因此我可以在新窗口中打开它的链接。我添加了一个新属性,这些属性需要在名为data-ext-link="true"
的新窗口中打开。在某些情况下,button
元素有一个onclick
,其中包含我需要发送给用户的location.href
。我怎样才能抓住使用jquery location.href
,所以我可以在我的函数中提供给window.open
?从jquery对象提取onclick location.href作为字符串
下面的函数对锚元素非常适用,但它在我的is('button')
if
语句中,它变得毛茸茸,并且不起作用,因为attr()
返回一个对象而不是字符串。它返回的对象是:
我的按钮代码:
<button data-ext-link="true" onclick="location.href='http://website/url_i_want'" class="btn2">Open it up</button>
$ .attr( '的onclick')回应:
function onclick(event) {
location.href = "http://website.com/url_i_want";
}
我的功能:
function extLinks() {
var extLinks = $('a[data-ext-link="true"], button[data-ext-link="true"]');
$.each(extLinks, function(){
if($(this).is('button')){
var link = $(this).attr('onclick'); // Here it needs to be a string.
link = link.match(/location.href='(.*)'/); //Won't work because it's an object.
link = link[1];
} else {
var link = $(this).attr('href');
}
$(this).unbind('click.extLink').bind('click.extLink',function(e){
e.preventDefault();
window.open(link);
});
});
}
更新:
我发现了以下关系ted问题,建议使用$.live
哪些被弃用我会用$.delagate()
来代替,但是这并没有完全解决这个问题,我需要通过onclick
中的作为目标来告诉这个按钮在新窗口中打开。
SOLUTION:
function extLinks() {
var extLinks = $('a[data-ext-link="true"], button[data-ext-link="true"]');
$.each(extLinks, function(){
if($(this).is('button')){
var link = this.onclick.toString().match(/location\.href\s*=\s*['"]([^'"]*)['"]/)[1];
} else {
var link = $(this).attr('href');
}
$(this).unbind('click.extLink').bind('click.extLink',function(e){
e.preventDefault();
window.open(link);
});
});
}
这里一定有其他事情发生。你可以发布一个按钮的HTML代码,这种方法不起作用吗?此外,您可能需要修改您的正则表达式 - 它不适用于您提供的示例。 – jnylen 2012-04-03 19:41:37
@jnylen:我为我的问题添加了更多细节。 – 2012-04-03 21:15:32
我已确认我的解决方案适用于我。请参阅http://nylen.tv/test-onclick.html。另外,如果您控制整个页面的HTML,那么重构代码就不那么需要这种体操(例如,使用URL的字典,或将URL放入一个'data-url '按钮或链接元素的属性)。 – jnylen 2012-04-03 21:29:44