我有这个 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
的来源与加载它的页面位于同一域中
最佳答案
我不确定你的 HTML 是什么样的,但是
$("twitter").attr("id", url);
应该是:
$(".twitter").attr("id", url);
更新:试试这段代码...您需要检测 iframe 是否也已加载 (demo)
$(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 对象。
关于javascript - 如何从 Iframe 内部的选择框中获取选定的值,并将其显示在外部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001030/