jQuery find location.href并替换为函数
如果使用jQuery启用javascript,我将把所有页面元素从单独的加载转到Ajax页面。我已经完成了大部分工作,但我需要检查onclick/onchange事件 我有这个:jQuery find location.href并替换为函数,jquery,Jquery,如果使用jQuery启用javascript,我将把所有页面元素从单独的加载转到Ajax页面。我已经完成了大部分工作,但我需要检查onclick/onchange事件 我有这个: $("select").each(function(){ if ($(this).attr('onchange')) { //CHECK FOR LOCATION.HREF } return false; }); 需要改变的是:
$("select").each(function(){
if ($(this).attr('onchange')) {
//CHECK FOR LOCATION.HREF
}
return false;
});
需要改变的是:
location.href='/calendar-of-events/'+escape(this.options[this.selectedIndex].value)+'/5/2011/
进入:
我该怎么做
谢谢
编辑:
我试过:
$("select").each(function(){
if ($(this).attr('onchange')) {
var ocval = $(this).attr('onchange');
ocval = ocval.replace('location.href=','pageload(');
ocval = ocval+')';
$(this).attr('onchange',ocval);
}
return false;
});
但这不起作用。onchange值是一个函数
function onchange(event) {
location.href = "/calendar-of-events/" + escape(this.options[this.selectedIndex].value) + "/5/2011/";
}
我将如何改变这一点 Javascript提供了一整套字符串操作,可以帮助您实现这一点。对于您提到的示例,一个简单的substr()可能就可以了。如果它更高级,您可能需要考虑使用正则表达式。 以下是一些入门教程:
我建议您不要使用
onchange
属性,只使用jQuery绑定事件
$("select").change(function(){
pageload("/calendar-of-events/"+escape($(this).val())+"/5/2011/");
});
如果您不能这样做,那么我建议您删除onchange
属性,并使用jQuery重新绑定事件
$("select").each(function() {
if($(this).attr('onchange')){
// Get the onchange function
var url = $(this).attr('onchange').toString()
// Regex to extract the location.href
.match(/location\.href\s?=\s?(['"].*['"])/);
// If we found a match
if(url !== null){
this.onchange = null; // Remove onchange event
$(this).change(function(){ // Rebind onchange
// Eval the location.href string, setting "this" to the select element
var urlstr = new Function('return '+url[1]).call(this);
// Call pageload with our eval'd url
pageload(urlstr);
});
}
}
});
演示:你回答了你自己的问题,太棒了!我正在寻找代码来替换location.href并将pageload函数包装在url周围。问题是我需要确保onchange中没有其他函数。在这种情况下,我可以将location.href=替换为pageload(然后在字符串末尾添加一个),但如果还有其他内容,我需要找到location.href的结尾。
返回false代码>在中。每个()
与中断相同代码>。如果在第一个元素之后中断,为什么不仅要选择第一个元素呢?在jQuery1.6中,您的代码可以工作,但在1.5中,$(this).attr('onchange')
返回一个函数,而不是字符串
。谢谢,我忽略了这一点。我想让它做所有的事情,我最初让它尝试覆盖onchange,但那只是让它做location.href和我在onchange中所做的。将尝试1.6次。谢谢。我在PHP中经常使用substr,但不幸的是,如果您在我的帖子中看到编辑,我不知道如何操作初始函数。一旦我获得location.href值,我就可以重新创建函数并覆盖,但问题是从函数中获取该值。谢谢。这已经接近我需要的了。url在IE9中返回匹配项,但在FF4中返回null。知道为什么吗?@fanFanFavorite:FF4在location.href=
中的等号前后添加了一个空格。我修复了代码,现在应该可以在FF4中工作了。
$("select").each(function() {
if($(this).attr('onchange')){
// Get the onchange function
var url = $(this).attr('onchange').toString()
// Regex to extract the location.href
.match(/location\.href\s?=\s?(['"].*['"])/);
// If we found a match
if(url !== null){
this.onchange = null; // Remove onchange event
$(this).change(function(){ // Rebind onchange
// Eval the location.href string, setting "this" to the select element
var urlstr = new Function('return '+url[1]).call(this);
// Call pageload with our eval'd url
pageload(urlstr);
});
}
}
});