2016-09-03 16 views
1

私はクリック機能を持っています。ユーザーがdivのどこかをクリックすると、正常に実行されます。しかし、div内にリンクがあります。ユーザーがリンクをクリックすると、その機能を実行したくないため、クリックするとリンクURLに移動します。div内のJqueryのクリック機能はありますが、div内のリンクの機能はありませんか?

HTML

<div id="container"> 
<a href="http://www.example.org"></a> 
</div> 

jqueryの私はそれを達成するために使用すべき方法

$(document.body).on('click', '[id="container"]' ,function(){ 
// do whatever 
}); 

答えて

1

私はあなたがこのような何かを行う場合は、動作するはずと信じて:

$("#container a").click(function(e) { 
     e.stopPropagation(); 
    }); 

はそれが役に立てば幸い! :)次のように

3

あなたは、クリックの対象を確認することができます。

$(document.body).on('click', '#container' ,function(e){ 
    if (e.target.id !== 'container') return; // not the element we want 
    // do whatever 
}); 

か、をdivの任意の他の子は、その後、それがa要素である場合を除いて、許可するかどう:

$(document.body).on('click', '#container' ,function(e){ 
    if (e.target.tagName === 'A') return; // not the element we want 
    // do whatever 
}); 
+0

スマート、感謝... FYI – user3304007

+0

'[ID = "コンテナが"]'通常#1 container' FYI –

+0

'として書き込まれ、そのため、含有量が動的に追加されました。 – user3304007

0
$(document).on('click', 'a',function (evt) { 
    evt.stopPropagation(); 
}); 
+0

これはうまくいきません。伝播はすでに起こっています。 – trincot

1

これを試してみてください:

$(document).ready(function(){ 

    $("#container").on("click",function(e){ 

     if(e.target.tagName == "DIV") { 
      fun(); 
     } 


     else if(e.target.tagName == "A") { 
      e.stopPropagation(); 
      } 


    }) 

    function fun() { 
     alert("Run function"); 
    } 
}) 

最終コード:

<html> 
 
    <title>This is test</title> 
 
    <head> 
 
    </head> 
 
    <body> 
 
     <div id="container">div 
 
      <a href="http://www.example.org">Link</a> 
 
     </div> 
 
     
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
     <script> 
 
    $(document).ready(function(){ 
 

 
     $("#container").on("click",function(e){ 
 

 
      if(e.target.tagName == "DIV") { 
 
       fun(); 
 
      } 
 

 

 
      else if(e.target.tagName == "A") { 
 
       e.stopPropagation(); 
 
       } 
 

 

 
     }) 
 

 
     function fun() { 
 
      alert("Run function"); 
 
     } 
 
    }) 
 
     </script> 
 
    </body> 
 
</html>

関連する問題