gpt4 book ai didi

javascript - 使用 Bootstrap 按钮单击和 jquery 更改 iframe 内容

转载 作者:行者123 更新时间:2023-11-27 22:34:56 25 4
gpt4 key购买 nike

我想通过单击引导按钮更改 iframe src url。javascript 代码适用于传统按钮,但是当我使用相同的代码通过 jquery 更改 iframe 时,会出现问题:(我还希望 iframe 在页面加载时变得随机)

引导元素(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/

关于javascript - 使用 Bootstrap 按钮单击和 jquery 更改 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com