2

JQuery .get メソッドを使用して、Web ページ (ページ 1) からコンテンツを取得し、メイン ページの div に表示しています。問題は、取得されたコンテンツにいくつかの JavaScript 呼び出しが含まれていることです。コンテンツは表示されていますが、Javascript メソッドが実行されていません。.js ファイルはすべてのページで参照されているため、メインでの js の可用性は問題になりません。

これは、メイン ページのコードです。ページ 1 の URL が .get 関数に渡されます。

$.get(url, function(response) {          
    var newContent = $(response).find("#right");      //Find the content section of the response
    var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
    var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.

    oldContent.replaceWith(newContent);
});

これは、ページ 1 の #right (div) のコードです。

Some html tags...    
<p><script type="text/javascript">abc7();</script></p>
<p><script>s(30)</script></p>
Some html tags...

関数 abc7 と s は、すべてのページのセクションで参照されている .js (通常の JavaScript ファイル) で使用できます。

s(30) は、サイズ 30 のテキスト フィールドを表示する必要があります。

4

2 に答える 2

6

インライン JavaScript は、実行しない限り実行されませんeval()。詳細については、こちらをご覧ください。

解決策は次のeval()ようになりますが、私はそれを悪い習慣と考えています:

$.get(url, function(response) {          
    var newContent = $(response).find("#right");      //Find the content section of the response
    var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
    var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.

    oldContent.replaceWith(newContent);


    //Find all inline script tags in the new content and loop through them
    newContent.find("script").each(function() {
        var scriptContent = $(this).html(); //Grab the content of this tag
        eval(scriptContent); //Execute the content
    });
});

より良い解決策は、タグに識別子/名前を設定し、#rightその特定のコンテンツに必要なコードを実行することです。

何かのようなもの:

<div id="right" data-page-name="index">
    <!-- Content -->
</div>

<div id="right" data-page-name="about-us">
    <!-- Content -->
</div>

ページに応じてコードを実行する関数にページ名を渡すだけの簡単なソリューションは、次のようになります。

$.get(url, function(response) {          
    var newContent = $(response).find("#right");      //Find the content section of the response
    var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
    var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.

    oldContent.replaceWith(newContent);

    var pageName = newContent.attr("data-page-name");

    pageSpecificActions(pageName);
});

function pageSpecificActions(pageName) {
    if (pageName == "index") {
        //Run the code for index page
    } else if (pageName == "about-us") {
        //Run the code for about us page.
    }   
};

これにより、JavaScript コードがインラインになるのを防ぎ、eval(). ページのコンテンツが変更されたときにイベントを使用するのがさらに良いでしょうが、今はこれで十分です。

于 2011-11-26T16:10:07.360 に答える
5

.load()の代わりに関数を使用できます.get()。応答に含まれるスクリプトを自動的に実行します。

ドキュメントは次のとおりです。

于 2013-07-19T15:19:37.360 に答える