用Bootstrap按钮点击和jquery改变iframe内容

Change iframe content with Bootstrap button click and jquery

本文关键字:jquery 改变 iframe 内容 Bootstrap 按钮      更新时间:2023-09-26

我想改变iframe src url从引导按钮点击。javascript代码与传统的按钮工作,但当我使用相同的代码改变jquery的iframe出错:(我也希望iframe在页面加载时随机)

bootstrap元素(html页面)

...
<div class="col-md-6">
    <a class="btn btn-primary" id="randomize">sekvanta ekzerco</a>
</div>
<div>
    <iframe id="question" src="url0" width="275"
                            height="650" frameborder="0" allowfullscreen="allowfullscreen">
</iframe>
</div>
...
    <script src="application.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  </body>

application.js

var sources = new Array()
sources[0] = 'url0'
sources[1] = 'url1'
sources[2] = 'url2'
sources[3] = 'url3'
var p = sources.length;
$(document).ready(function(){
    var randomSource = Math.round(Math.random()*(p-1));
    $('#question').attr('src', 'sources[randomSource]');
}
$('#randomize').click(function() {
    var randomSource = Math.round(Math.random()*(p-1));
    $('#question').attr('src', 'sources[randomSource]');
}

您可以删除sources[randomSource]中的单引号,因为浏览器会将其解释为文字而不是计算表达式。

$('#question').attr('src', sources[randomSource]);

完整片段:

var sources = new Array()
sources[0] = 'url0'
sources[1] = 'url1'
sources[2] = 'url2'
sources[3] = 'url3'
var p = sources.length;
$('#randomize').click(function() {
    var randomSource = Math.round(Math.random()*(p-1));
    console.log(sources[randomSource]);
    $('#question').attr('src', sources[randomSource]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="randomize">
Click me
</button>
<div id="question">
</div>

JSFiddle演示Bootstrap版本。

https://jsfiddle.net/fz6yythy/