使用RegEx更改查询字符串

时间:2016-12-29 08:32:39

标签: javascript jquery html regex

我想使用按钮点击替换给定网址的部分。当我点击播放按钮时需要更改autoplay=0 to autoplay=1,当我点击关闭按钮时需要更改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>

2 个答案:

答案 0 :(得分: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>

代码可以干洗如下

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);
    });
});

答案 1 :(得分:1)

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

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

详细了解attr方法here