簡體   English   中英

用JS調用用戶定義的jQuery函數

[英]Call user defined jQuery function with JS

我使用jQuery窗口libray https://github.com/humaan/Modaal

這樣觸發事件$("class of element").modaal({arg1, arg2,...});

---我在這里更新了我的問題,使其更通用,並使用了iframe / HTML而不是外部svg-

為了觸發一個元素,例如在iframe中加載的外部HTML中,我將以下代碼應用於iframe:

<iframe src="External.html" id="mainContent" onload="access()"></iframe>

調用此函數:

function access() {
var html = document.getElementById("mainContent").contentDocument.getElementById("IDofDIVelement");
html.addEventListener('click', function() {clicker();});
}
function clicker()
{
// console.log('hooray!');
$("#mainContent").contents().find("IDofDIVelement").modaal({});
//return false;
}

實際上,它只會在第二次單擊時起作用。 知道我沒有適當考慮的事情嗎?

最好

您無需等待Windows加載,而只需要iframe:

$(function() {
    $("#mainContent").bind("load",function(){
        var myIframeElement = $(this).contents().find(".modaal");

        myIframeElement.modaal({
            content_source: '#iframe-content',
            type: 'inline',
        });
    });
});

之所以不起作用,是因為jQuery嘗試附加該功能時,iframe並未完全加載。 由於$(document).ready(function(){}不起作用,解決方法是使用

$( window ).on( "load",function() {
$("#mainContent").contents().find("IDofDIVelement").modaal({});
});

這可以正常工作,以將功能附加到iframe中的元素。

實際上,在覆蓋層再次打開和關閉后,模態將消失。 因此,也許有人也想觸發iframe元素以獲得模態,這是可以解決此問題的設置。 (可以通過@SvenLiivaks回答對其進行優化):

 $(window).on("load", function() {
     reload();
    });

function reload() {
    var length = $("#iframeID").contents().find("#IDofDIVelement").length;
    // The following check will return 1, as the iframe exists.
    if (length == 0) {
        setTimeout(function() { reload() }, 500);
    } else {
        $("#iframeID").contents().find("#IDofDIVelement").modaal({
            content_source: '#modalwrapper',
            overlay_close: true,
            after_close: function reattach() {
                reload();
            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM