所以我目前正在开发一个小型样式指南应用程序,部分功能是有一个沙箱区域,某些模块被加载到iframe中(以便能够模拟媒体查询)。现在,在创建iframe以及相关样式和脚本之后动态插入此内容。
非事件处理程序脚本可以很好地工作,例如警告框,但是单击处理程序似乎不起作用。 Jquery装得很好所以我已经把它排除了。
这是插入代码的示例
<!-- Accordion-->
<div class="accordion module-suggestions col-sm-3 col-xs-12 pull-right hidden-xs">
<h4>Most popular</h4>
<div class="accordion-section active">
<ul>
<li>Why your CCTV could land you in jail<span class="result-type case-study"></span>
</li>
<li>How to measure performance of SMEs<span class="result-type guides"></span>
</li>
<li>How to measure performance <span class="result-type checklist"></span>
</li>
</ul>
</div>
<h4>Most recent</h4>
<div class="accordion-section">
<ul>
<li>Why your CCTV could land you in jail<span class="result-type case-study"></span>
</li>
<li>How to measure performance of SMEs<span class="result-type guides"></span>
</li>
<li>How to measure performance <span class="result-type checklist"></span>
</li>
</ul>
</div>
<h4>Recommended</h4>
<div class="accordion-section">
<ul>
<li>Why your CCTV could land you in jail<span class="result-type case-study"></span>
</li>
<li>How to measure performance of SMEs<span class="result-type guides"></span>
</li>
<li>How to measure performance <span class="result-type checklist"></span>
</li>
</ul>
</div>
</div>
<!-- / Accordion -->
<script>
function accordion() {
var accordion = $('.accordion h4');
var accordionSection = $('div.accordion-section');
$(accordion).on("click", function(e) {
if (!$(this).next(accordionSection).is(":visible")) {
$(accordionSection).is(":visible") && $(accordionSection).slideUp();
$(this).next(accordionSection).slideDown();
}
});
}
accordion();
</script>
为了澄清,代码直接放在iframe的HTML中,我不会从它的父级调用它。
负责将html / js插入iframe的代码:
iframePreview.contents()。find('html')。html(libraryScripts +'\ n'+ moduleHtmlAndJs);
知道如何让这些点击处理程序正常运行吗?
答案 0 :(得分:0)
您可以使用slideToggle并访问处理程序中最近的accordion-section来简化此操作。
试试这个:
function accordion() {
$('.accordion').on("click","h4", function() {
var accordionSection = $(this).next('div.accordion-section');
$(accordionSection).slideToggle();
});
}
accordion();
答案 1 :(得分:0)
似乎.html()
删除了<script>
个标签。
How to prevent jquery from removing the <script> tags
尝试改为使用.innerHTML
:
iframePreview.contents().find('html').[0].innerHTML = libraryScripts + '\n' + moduleHtmlAndJs;
答案 2 :(得分:0)
您可以不在iframe contentWindow本身的全局级别创建函数,而不是将脚本注入iframe吗?
例如:
iframePreview.contentWindow.accordion = function(){
$('.accordion').on("click","h4", function() { ... etc...});
}
然后在插入html后调用该函数:
iframePreview.contentWindow.accordion();
所以 - 你从iFrame上的父窗口设置函数,并在HTML到位后从父窗口调用它。