4

我在 HTML 中有这个选择框,它所在的页面正在通过 iframe 加载到另一个页面(都在我的网站上)。我希望能够从选择框(iframe 内部)中获取选定的值,并将其显示在外部。这是我拼凑的一些代码,但我不知道我是否做得对:

<script>
$('#iframe').contents().find('#cds').change(function() {
    var selectVal = $(this).val();
    url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on'; 
    $("twitter").attr("id", url);
});
</script>

有什么建议吗?

澄清

  • 我的<select>元素在iframe
  • 我想在iframe
  • 的来源与iframe加载它的页面在同一个域中
4

1 回答 1

1

我不确定你的 HTML 是什么样的,但是

$("twitter").attr("id", url);

应该是:

$(".twitter").attr("id", url);

更新:试试这段代码......你需要检测 iframe 是否也已加载(演示

$(function () {
    // define this here because we're changing the ID
    var $twitter = $('#twitter');
    // bind to select inside iframe
    $('#iframe').on('load', function () {
        $(this).contents().find('#cds').change(function () {
            var selectVal = $(this).val();
            url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
            $twitter.attr("id", url).text(url);
        }).change(); // trigger change to get initial value
    });
});

此外,由于我们正在更改 twitter 的 ID,因此我们需要保存该 jQuery 对象。

于 2013-04-14T16:07:11.150 回答