jQuery-根据select值更改iframe-src

jQuery - change iframe src based on select value

本文关键字:iframe-src 根据 select jQuery-      更新时间:2023-09-26

现在,我正试图根据选择的内容更改iframe-src值。我有多个selects/iframe,所以我需要一些东西来处理所有实例。

<div class="wrap">
    <select class="changer">
        <option value="http://stackoverflow.com">StackOverflow</option>
        <option value="http://google.com">Google</option>
        <option value="http://yahoo.com">Yahoo</option>
        <option value="http://twitter.com">Twitter.com</option>
    </select>
    <iframe src="http://stackoverflow.com"></iframe>
</div>
<div class="wrap">
    <select class="changer">
        <option value="http://stackoverflow.com">StackOverflow</option>
        <option value="http://google.com">Google</option>
        <option value="http://yahoo.com">Yahoo</option>
        <option value="http://twitter.com">Twitter.com</option>
    </select>
    <iframe src="http://stackoverflow.com"></iframe>
</div>

CSS:

.wrap {
    width:50%;
    float:left;
}
iframe {
    width:100%;
    height:500px;
display:block;
}

jQuery:

$('.changer').change(function () {
    $(this).attr('src', this.value);
});

您更改的是select元素的src属性,而不是iframe元素。

给定HTML,您可以使用.next('iframe')来更改相邻iframe元素的源。

此处示例

$('.changer').change(function () {
    $(this).next('iframe').attr('src', this.value);
});

试试这个:

$('.changer').change(function () {
    $(this).next().attr('src', this.value);
});