如何根据<select>更改iframe的src属性使用 javascript/jquery 的值? [英] How to change src attribute of iframe based on <select> value using javascript/jquery?
问题描述
我有一个大于 20MB(太大)的网页,问题是每个 youtube 视频大约有 500 KB!我想使用 HTML5 选择选项列出 30 多个视频.该值是 YouTube 视频 ID.然后用户从下拉选项中选择所需的视频.然后在 iframe 中加载视频.
I have a webpage of >20MB (too big) and the problem is that the youtube videos are ~500 KB each! I want to use an HTML5 select option to list 30+ videos. The value is the youtube video ID. User then selects from the dropdown options the desired video. Then the video loads in the iframe.
<form>
<select id="dynamic_select">
<option value="" selected>Pick a Key and Peele youtube video</option>
<option value="pSDTmJtE-Bc">Little Homie</option>
<option value="Dd7FixvoKBw">Substitute Teacher</option>
<option value="iGAMbNKcN1U">Fronthand Backhand</option>
</select>
</form>
这是工作模板",但我想用选定的选项值替换 src 字符串中的nlD9JYP8u5E".可以这样做吗?
This is the working "template" but I want to replace the "nlD9JYP8u5E" in the src string with the selected option value. Can this be done?
<article>
<iframe src="https://www.youtube.com/embed/nlD9JYP8u5E?rel=0&showinfo=0"></iframe>
</article>
推荐答案
在 .replace()
中使用正则表达式来改变 iframe 的 src
属性.在jquery中,我在选择元素
Use regex in .replace()
to changing src
attribute of iframe. In jquery the .attr()
change attribute of element that i used it in change
event listener of select element
$("#dynamic_select").change(function(){
var val = $(this).val();
$("iframe").attr("src", function(i, a){
return a.replace(/(?<=embed\/)[^?]+/, val);
});
});
$("#dynamic_select").change(function(){
var val = $(this).val();
$("iframe").attr("src", function(i, a){
return a.replace(/(?<=embed\/)[^?]+/, val);
});
console.log($("iframe").attr("src"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="dynamic_select">
<option value="" selected>Pick a Key and Peele youtube video</option>
<option value="pSDTmJtE-Bc">Little Homie</option>
<option value="Dd7FixvoKBw">Substitute Teacher</option>
<option value="iGAMbNKcN1U">Fronthand Backhand</option>
</select>
</form>
<article>
<iframe src="https://www.youtube.com/embed/nlD9JYP8u5E?rel=0&showinfo=0">
</iframe>
</article>
这篇关于如何根据<select>更改iframe的src属性使用 javascript/jquery 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!