【问题标题】:How do i properly create a variable from a string in Javascript/jQuery?如何从 Javascript/jQuery 中的字符串正确创建变量?
【发布时间】:2017-10-18 18:03:20
【问题描述】:

我希望使用字符串“activeVideo”作为变量,但我无法让它工作。我想我已经很接近做对了,但我已经被困了好几个小时了……我做错了什么?

firstVideo = 'https://www.youtube.com/embed/kxopViU98Xo?rel=0&showinfo=0?ecver=2;autoplay=1';
secondVideo = 'https://www.youtube.com/embed/FWO5Ai_a80M?ecver=2;autoplay=1';
jQuery('.play-circle').click(function() {
  console.log(this.id + 'Video');
  activeVideo = this.id + 'Video';
  jQuery('.play-circle').fadeOut(0);
  jQuery('.video').fadeIn(0);
  jQuery('.video-close').fadeIn(0);
  jQuery('#' + this.id + 'Video').attr('src', activeVideo);
});
jQuery('.video-close').click(function() {
  console.log('closing video');
  jQuery(activeVideo).attr('src', '');
  jQuery('.video').fadeOut(0);
  jQuery('.video-close').fadeOut(0);
  jQuery('.play-circle').fadeIn(0);
});
body {
  background-color: #000000;
}

.banner-wide {
  position: relative;
  height: 720px;
  background: url('https://picsum.photos/1000/500') center/cover;
}

.banner-wide .text {
  width: 30%;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  margin-left: 7%;
}

.banner-wide .text h3,
.banner-wide .text p {
  text-align: left;
  color: #ffffff;
}

.video-thumbnail {
  z-index: 11;
  position: relative;
  right: 0;
  top: 0;
  width: 50%;
  height: 360px;
  cursor: pointer;
  float: right;
  padding: 5px;
  box-sizing: border-box;
}

.play-circle {
  width: 100%;
  height: 100%;
  background: url('http://addplaybuttontoimage.way4info.net/Images/Icons/13.png') no-repeat center/150px rgba(0, 0, 0, 0.7);
}

.video {
  display: none;
  width: 100%;
  height: 360px;
  position: relative;
  right: 0;
  top: 0;
}

.video-close {
  display: none;
  position: absolute;
  width: 20px;
  height: 20px;
  top: 14px;
  right: 20px;
  cursor: pointer;
  background: url('http://freevector.co/wp-content/uploads/2013/03/8934-close-button1.png') no-repeat center center / 20px rgba(255, 255, 255, 1);
  border-radius: 100px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="banner-wide owc">
  <div class="video-thumbnail">
    <div id="first" class="play-circle"></div>
    <div class="video-close"></div>
    <iframe class="video" id="firstVideo" width="375" height="225" frameborder="0" allowfullscreen></iframe>
  </div>
  <div class="video-thumbnail">
    <div id="second" class="play-circle"></div>
    <div class="video-close"></div>
    <iframe class="video" id="secondVideo" width="375" height="225" frameborder="0" allowfullscreen></iframe>
  </div>
</div>

【问题讨论】:

  • 你根本不知道。至少不是正确
  • 请不要链接到第三方网站,因为这些链接可能会随着时间的推移而失效。只需在此处以代码 sn-p 的形式发布您的代码。
  • 只需将activeVideo = this.id + 'Video'; 也放入 close 函数中,它应该可以工作。请注意,您需要声明变量!!,为此使用const,let,var。然后你的代码会在这种情况下崩溃,你可以回到正确的轨道
  • 正确的方法是创建一个数组。我还修复了您的其他代码:jsfiddle.net/Lta1mydu

标签: javascript jquery string variables concatenation


【解决方案1】:

您可以定义一个对象,而不是两个单独的变量:

var vids = {first: 'https://www.youtube.com/embed/kxopViU98Xo?rel=0&amp;showinfo=0?ecver=2;autoplay=1',
           second: 'https://www.youtube.com/embed/FWO5Ai_a80M?ecver=2;autoplay=1'};

然后使用以id为key的对象进行索引:

jQuery('.play-circle').click(function(){          
    jQuery('.play-circle').fadeOut(0);
    jQuery('.video').fadeIn(0);
    jQuery('.video-close').fadeIn(0);
    jQuery('#' + this.id + 'Video').attr('src',vids[this.id]);
});

【讨论】:

    【解决方案2】:

    字符串是不可执行的,不能仅仅用来代替评估代码。

    但是,对象结构只不过是键(即字符串)和值,因此您可以将字符串(通过数组索引表示法)传递给对象以提取该键的值。

    由于您正在构建的字符串对应于元素的id,您可以将该字符串作为“键”传递给window 对象,它将解析正确的对象,因为带有ids 的元素变为全局属性。

    然后,如果您将视频的 URL 存储在另一个对象中,您可以将字符串传递给该对象以提取您需要的 URL。

    你还需要声明你的变量并给它们适当的范围。

    $(function(){
    
      // By storing the data in an object with key/value pairs, the key names can be
      // accessed via the scope of the object later
      var obj = {
        firstVideo : 'https://www.youtube.com/embed/kxopViU98Xo?rel=0&amp;showinfo=0?ecver=2;autoplay=1',
        secondVideo : 'https://www.youtube.com/embed/FWO5Ai_a80M?ecver=2;autoplay=1'
      }
    
      var activeVideo = ""; // Need to declare this in a scope that can be accessed from both functions
    
    		jQuery('.play-circle').click(function(){
    
          activeVideo = this.id + 'Video';      
          jQuery('.play-circle').fadeOut(0);
    			jQuery('.video').fadeIn(0);
    			jQuery('.video-close').fadeIn(0);
          
          // Get the element stored in the global property and pass to jQuery, then
          // get the key out of the storage object and use as the source:
    			jQuery(window[activeVideo]).attr('src', obj[activeVideo]);
          // Test:
    			console.log(jQuery(window[activeVideo]).attr('src')); 
    		});
    
    		jQuery('.video-close').click(function(){
    			console.log('closing video');
          // Elements with id's become global properties, so the string
          // of their id can be passed as a key to the window object:
    			$(window[activeVideo]).attr('src','');
    			jQuery('.video').fadeOut(0);
    			jQuery('.video-close').fadeOut(0);
    			jQuery('.play-circle').fadeIn(0);
    		});
    });
    body {
      background-color: #000000;
    }
    .banner-wide {
    	position: relative;
    	height: 720px;
    	background: url('https://picsum.photos/1000/500') center/cover;
    }
    .banner-wide .text {
    	width: 30%;
    	position: relative;
    	top: 50%;
    	transform: translateY(-50%);
    	margin-left: 7%;
    }
    .banner-wide .text h3,
    .banner-wide .text p {
    	text-align: left;
    	color: #ffffff;
    }
    .video-thumbnail {
    	z-index: 11;
    	position: relative;
    	right: 0;
    	top: 0;
    	width: 50%;
    	height: 360px;
    	cursor: pointer;
      float: right;
      padding: 5px;
      box-sizing: border-box;
    }
    .play-circle {
    	width: 100%;
    	height: 100%;
      background: url('http://addplaybuttontoimage.way4info.net/Images/Icons/13.png') no-repeat center/150px rgba(0,0,0,0.7);
    }
    .video {
    	display: none;
    	width: 100%;
    	height: 360px;
    	position: relative;
    	right: 0;
    	top: 0;
    }
    .video-close {
    	display: none;
    	position: absolute;
    	width: 20px;
    	height: 20px;
    	top: 14px;
    	right: 20px;
    	cursor: pointer;
    	background: url('http://freevector.co/wp-content/uploads/2013/03/8934-close-button1.png') no-repeat center center / 20px rgba(255,255,255,1);
    	border-radius: 100px;
    	box-shadow: 0 0 20px rgba(0,0,0,0.1);
    	z-index: 1;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="banner-wide owc">
            <div class="video-thumbnail">
                <div id="first" class="play-circle"></div>
                <div class="video-close"></div>
                <iframe class="video" id="firstVideo" width="375" height="225" frameborder="0" allowfullscreen></iframe>
            </div>
      <div class="video-thumbnail">
                <div id="second" class="play-circle"></div>
                <div class="video-close"></div>
                <iframe class="video" id="secondVideo" width="375" height="225" frameborder="0" allowfullscreen></iframe>
            </div>
        </div>

    【讨论】:

    • 感谢所有建议。这个是我需要的。再次,非常感谢! :)
    • 嗯好的。我刚刚发现这个解决方案在 iOS 上不起作用。你知道为什么会这样吗?
    • @alc 您在开发者控制台中看到了什么消息。我想不出这段代码中有什么不标准的地方。
    • 一如既往,给猫剥皮的方法不止一种。这也是一个很好的答案;)
    【解决方案3】:

    这将解决它...

    jQuery('#' + this.id + 'Video').attr('src',eval(activeVideo));
    

    免责声明:正如您从下面的 cmets 中看到的那样,它并不受欢迎。我对此很清楚。你可以停止投票。如果您是那些认为eval() 是邪恶的人之一,请不要使用它。但这是一个可行的解决方案,可以快速轻松地解决问题,并且不使用它(恕我直言)将是过早的优化。当然可以随意进行自己的研究来决定是否走这条路。

    【讨论】:

    • 这会回答问题,但不会。
    • @ScottMarcus 我不同意这个答案,但这是不正确的。如果使用得当就好了。我能想到的一个例子是在构建模板引擎时。
    • 我知道eval() 因性能原因而受到不好的评价,但在这种情况下,它是最简单的解决方案,不使用它是过早的优化。简单地说“永远不是解决任何问题的好方法”是教条主义的。这是一个可行的工具,使用它。
    • @ChrisGeirman 这不仅仅是出于性能原因。这是出于安全和范围的原因,不需要解决任何问题。
    • @RobertBolton 我们可以整天引用文章,但如果您不必使用eval() 来解决问题并且它会打开所有这些问题,那么为什么还要使用它呢?跨度>
    猜你喜欢
    • 1970-01-01
    • 2022-06-25
    • 2011-01-06
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多