Javascript 使用RegEx更改querystring
我想使用按钮单击替换给定URL的一部分。当我单击播放按钮时,需要更改Javascript 使用RegEx更改querystring,javascript,jquery,html,regex,Javascript,Jquery,Html,Regex,我想使用按钮单击替换给定URL的一部分。当我单击播放按钮时,需要更改autoplay=0到autoplay=1,当我单击关闭按钮时,需要更改autoplay=1到autoplay=0 jQuery(文档).ready(函数($){ $('.playButton')。单击(函数(){ 警惕(“玩”); $(“iframe”).src=src.replace(/\&autoplay\=\d/,“&autoplay=“+1”); }); $(“.close_图标”)。单击(函数(){ 警报(“关闭”
autoplay=0到autoplay=1
,当我单击关闭按钮时,需要更改autoplay=1到autoplay=0
jQuery(文档).ready(函数($){
$('.playButton')。单击(函数(){
警惕(“玩”);
$(“iframe”).src=src.replace(/\&autoplay\=\d/,“&autoplay=“+1”);
});
$(“.close_图标”)。单击(函数(){
警报(“关闭”);
$(“iframe”).src=src.replace(/\&autoplay\=\d/,“&autoplay=“+0”);
});
});代码>
玩
关闭
如您所见,控制台出现错误未捕获引用错误:src未定义
,这意味着您试图使用不存在的属性,请尝试:
$("iframe").attr("src", function(index, value){ return value.replace("autoplay=0", "autoplay=1") })
阅读有关attr方法的更多信息。如您所见,控制台中出现错误未捕获引用错误:未定义src
,这意味着您试图使用不存在的属性,请尝试:
$("iframe").attr("src", function(index, value){ return value.replace("autoplay=0", "autoplay=1") })
阅读更多关于attr方法的信息。你不需要正则表达式。可以进行字符串替换
$(“iframe”).src
不会设置iframe
的src
属性的值。使用attr()
更改元素的属性
jQuery(文档).ready(函数($){
$('.playButton')。单击(函数(){
$(“iframe”).attr('src',function(i,oldSrc){
if(oldSrc.indexOf('autoplay')=-1){
//如果URL上没有自动播放,请添加它
oldSrc+='&自动播放=1';
}
返回oldSrc.replace('autoplay=0','autoplay=1');
});
});
$(“.close_图标”)。单击(函数(){
$(“iframe”).attr('src',function(i,oldSrc){
返回oldSrc.replace('autoplay=1','autoplay=0');
});
});
});代码>
玩
关闭
此操作不需要正则表达式。可以进行字符串替换
$(“iframe”).src
不会设置iframe
的src
属性的值。使用attr()
更改元素的属性
jQuery(文档).ready(函数($){
$('.playButton')。单击(函数(){
$(“iframe”).attr('src',function(i,oldSrc){
if(oldSrc.indexOf('autoplay')=-1){
//如果URL上没有自动播放,请添加它
oldSrc+='&自动播放=1';
}
返回oldSrc.replace('autoplay=0','autoplay=1');
});
});
$(“.close_图标”)。单击(函数(){
$(“iframe”).attr('src',function(i,oldSrc){
返回oldSrc.replace('autoplay=1','autoplay=0');
});
});
});代码>
玩
关闭
使用attr()
更改iframe的src
属性<代码>$('iframe').attr('src',函数(i,oldSrc){返回oldSrc.replace('autoplay=0','autoplay=1');})
@tushar您的帖子运行正常。请重新发布。这里是您的ans。我将更新您的答案。我需要检查自动播放是否在src中,然后追加。因此,可能存在URL中没有autoplay=n
的情况?使用attr()
更改iframe的src
属性<代码>$('iframe').attr('src',函数(i,oldSrc){返回oldSrc.replace('autoplay=0','autoplay=1');})
@tushar您的帖子运行正常。请重新发布。这是您的ans帖子。我将更新您的答案我需要检查自动播放是否在src中,然后追加。因此,URL中可能没有autoplay=n
?我需要检查自动播放是否在src中,然后append@user3386779要检查其他字符串中是否存在字符串,您可以使用indexOf()
。在您的情况下,您还可以使用/autoplay=\d/.test(url)
@user3386779。我在播放
回调中的if
中添加了条件。我想没有必要在stop
callback中执行同样的操作。@user3386779我已经从上面代码段的URL中删除了autoplay
。当你点击play
按钮时,你可以看到添加了autoplay
。我需要检查autoplay是否在src中,然后append@user3386779要检查其他字符串中是否存在字符串,可以使用indexOf()
。在您的情况下,您还可以使用/autoplay=\d/.test(url)
@user3386779。我在播放
回调中的if
中添加了条件。我想没有必要在stop
callback中执行同样的操作。@user3386779我已经从上面代码段的URL中删除了autoplay
。单击play
按钮可以看到添加了autoplay
。