2017-12-21 28 views
0

どうすれば、htmlファイルがwindow.locationを使用した後で別の別のhtmlファイルのeventListenerにアクセスするのを防ぐことができますか?どちらのhtmlファイルも同じ外部ファイルを使用します jsファイル 。おかげUncaught TypeError:ヌルエラーの 'addEventListener'のヌルエラーを読み取ることができません

私のコード

index.htmlを

<body> 

<form id=form> 
    <input type="button" value="submit"> 
</form> 

<script src="main.js"></script> 
</body> 

post.htmlファイル

<body> 
    <script src="main.js"></script> 
</body> 

main.jsは

document.getElementById("form").addEventListener("click", function(e){ 
    console.log("hello"); 
    window.location = "post.html"; 
    e.preventDefault(); 
}); 
を提出します
+0

..... – epascarello

+1

あり、いくつかの方法がありますが、最も簡単なのは、2ページの要素に異なるID(IDやクラスなど)を与えることです。次に、JavaScriptを更新して目的のページの一意の要素のみをターゲットにします。また、あなたの '

' IDには引用符が必要です。 –

+0

私はindex.htmlファイルのformタグにformのidを付けました。 post.htmlファイルにリダイレクトされますが、addeventlistenerエラー –

答えて

0

これを解決する1つの方法は、イベントリスナーをパス名を確認するifステートメントの周りにラップすることです。

あなたはそれがページ上にあるかどうかを確認するために、特定のIDや何かを経由して、それを結合するか、またはロジックを追加する必要があるよりも、まあ

if (window.location.pathname === '/index.html') { 
 
    // do stuff in here that you want to execute for the index.html page 
 
    document.getElementById("form").addEventListener("click", function(e){ 
 
     console.log("hello"); 
 
     window.location = "post.html"; 
 
     e.preventDefault(); 
 
    }); 
 
}

関連する問題