2016-12-29 54 views
0

我想用按钮click.When我点击播放按钮,需要改变autoplay=0 to autoplay=1更换指定的URL的一部分的查询字符串,当我点击关闭按钮后,有变更autoplay=1 to autoplay=0更改使用正则表达式

jQuery(document).ready(function($) { 
 
    $('.playButton').click(function() { 
 
    alert('play'); 
 
    $("iframe").src = src.replace(/\&autoplay\=\d/, "&autoplay=" + 1); 
 
    }); 
 

 
    $(".close_icon").click(function() { 
 
    alert('close'); 
 
    $("iframe").src = src.replace(/\&autoplay\=\d/, "&autoplay=" + 0); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<iframe src="https://www.youtube.com/embed/C0DPdy98e4c?width=640&autoplay=1"></iframe> 
 
<div class="playButton">Play</div> 
 
<div class="close_icon">Close</div>

+1

使用'ATTR()'改变iframe的'src'属性。 '$('iframe')。attr('src',function(i,oldSrc){return oldSrc.replace('autoplay = 0','autoplay = 1');});' – Tushar

+0

@tushar你的帖子正在工作fine.Please再次张贴 – user3386779

+1

这是[完整代码(https://jsfiddle.net/tusharj/vqzkn1gp/) – Tushar

回答

2

您不需要RegEx。可以完成字符串替换。

$("iframe").src将不会设置src属性iframe的属性值。使用attr()更改元素的属性。

jQuery(document).ready(function($) { 
 
    $('.playButton').click(function() { 
 
    $("iframe").attr('src', function(i, oldSrc) { 
 
     if (oldSrc.indexOf('autoplay') === -1) { 
 
     // If autoplay is not on URL, add it 
 
     oldSrc += '&autoplay=1'; 
 
     } 
 

 
     return oldSrc.replace('autoplay=0', 'autoplay=1'); 
 
    }); 
 
    }); 
 

 
    $(".close_icon").click(function() { 
 
    $("iframe").attr('src', function(i, oldSrc) { 
 
     return oldSrc.replace('autoplay=1', 'autoplay=0'); 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<iframe src="https://www.youtube.com/embed/C0DPdy98e4c?width=640"></iframe> 
 
<div class="playButton">Play</div> 
 
<div class="close_icon">Close</div>


的代码可以作为DRY'd遵循

jQuery(document).ready(function($) { 
    // To update the value of autoplay in the URL of iframe src attribute 
    var changeAutoplay = function(newValue) { 
     $('iframe').attr('src', function(i, oldSrc) { 
      return oldSrc.replace(/autoplay=\d/, 'autoplay=' + newValue); 
     }); 
    }; 

    $('.playButton').click(function() { 
     changeAutoplay(1); 
    }); 

    $(".close_icon").click(function() { 
     changeAutoplay(0); 
    }); 
}); 
+0

我需要检查自动播放在src中,然后附加 – user3386779

+0

@ user3386779要检查一个字符串是否存在于其他字符串中,可以使用'indexOf()'。在你的情况下,你也可以使用'/autoplay=\d/.test(url)' – Tushar

+0

你可以请更新你的小提琴请 – user3386779

1

正如您所见,控制台Uncaught ReferenceError: src is not defined存在错误,这意味着您尝试使用不存在的属性,请尝试:

$("iframe").attr("src", function(index, value){ return value.replace("autoplay=0", "autoplay=1") }) 

阅读更多关于attr方法here