点击删除iFrame src数据属性

时间:2018-10-04 14:37:56

标签: javascript jquery html

我有一个vimeo播放器,其src ID是从data-vimeo上的属性div拾取的。

以下示例:

<div class="js-video-btn" data-vimeo="286031821">Button Link</div>

我的vimeo播放器的iframe如下

<iframe class="vimeo-frame" src='https://player.vimeo.com/video/' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

直到获取到data-vimeo URL的src属性,直到此https://player.vimeo.com/video/286031821

我用jQuery实现了这一点,并且一切正常。但是,我想做的是单击另一个按钮,它删除了data-vimeo属性,并保留了src URL:https://player.vimeo.com/video/

这是我的jQuery:

$('.js-video-btn').click(function() {
    var video=$(this).data('vimeo');
    $('.vimeo-frame').attr('src', $('.vimeo-frame').attr('src') + video );
});

$('.video-close').click(function(){
    $('.vimeo-frame').removeAttr('src', $('.vimeo-frame').attr('src'));
});

我正在使用removeAttr,但是此操作会删除整个URL,我只想删除data-vimeo ID。实现此目标的最佳方法是什么?

这里也是jsFiddle

2 个答案:

答案 0 :(得分:0)

删除最后一个正斜杠之后的所有字符。
另外,不要多次添加视频ID。

这是一个工作示例:

$(".js-video-btn").click(function() {
  var video = $(this).data("vimeo");
  var $videoFrame = $(".vimeo-frame");
  var src = $videoFrame.attr("src");

  // Make sure video id is not added twice
  if (src.length - 1 === src.lastIndexOf("/")) {
    $videoFrame.attr("src", src + video);
  }
});

$(".video-close").click(function() {
  var $videoFrame = $(".vimeo-frame");
  var src = $videoFrame.attr("src");
  
  // Trim the characters after the last forward slash
  $videoFrame.attr("src", src.substr(0, src.lastIndexOf("/") + 1));
});
.link-txt {
  cursor: pointer;
  background: red;
  padding: 10px;
  color: white;
  text-align: center;
}

.video-close {
  width: 100%;
  display: block;
  background: blue;
  color: white;
  border: none;
  padding: 10px;
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link-txt js-video-btn" data-vimeo="286031821">Button Link to add video to iframe</div>

<section class="video-popup">
  <div class="video-inner">
    <div class="clearfix">
      <button type="button" class="btn btn-secondary video-close">close video</button>
    </div>
    <div class='o-embed-container'>
      <iframe class="vimeo-frame" src='https://player.vimeo.com/video/' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
    </div>
  </div>
</section>

答案 1 :(得分:-1)

听起来您的网址看起来像https://player.vimeo.com/video/123,而您只想要https://player.vimeo.com/video/

如果是这种情况,请查看下面的代码,使用它来设置src。

var test="https://player.vimeo.com/video/123"
test = test.substr(0,test.lastIndexOf("/"));

这将保留结果“ https://player.vimeo.com/video