development

태그의

big-blog 2020. 7. 13. 23:08
반응형

태그의 preventDefault ()


링크를 클릭 할 때 div를 위아래로 슬라이드하여 표시하거나 숨기는 html / jquery가 있습니다.

<ul class="product-info">
  <li>
    <a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
}

내 질문은 : preventDefault()링크 역할을하고 #URL 끝에 추가 하고 페이지 상단 으로 이동하는 링크를 중지하는 데 어떻게 사용 합니까?

올바른 구문을 알 수 없으므로 preventDefault ()가 함수가 아니라는 오류가 계속 발생합니다.


다음과 같은 것을 시도하십시오 :

$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});

다음은 jQuery 설명서 의 페이지입니다.


href속성을 다음과 같이 설정하십시오.href="javascript:;"

<ul class="product-info">
  <li>
   <a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a>
  <div class="toggle">
    <p>CONTENT TO SHOW/HIDE</p>
  </div>
 </li>
</ul>

return false3 가지 결과가 발생하므로을 사용하지 않는 것이 좋습니다 .

  1. event.preventDefault ();
  2. event.stopPropagation ();
  3. 콜백 실행을 중지하고 호출되면 즉시 반환합니다.

따라서 이런 상황에서는 실제로 만 사용해야합니다 event.preventDefault();

Archive of article - jQuery Events: Stop (Mis)Using Return False


<ul class="product-info">
  <li>
    <a href="javascript:void(0);">YOU CLICK THIS TO SHOW/HIDE</a>
      <div class="toggle">
        <p>CONTENT TO SHOW/HIDE</p>
      </div>
  </li>
</ul>

Use

javascript:void(0);


Alternatively, you could just return false from the click event:

 $('div.toggle').hide();
 $('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
+ return false; 
 });

Which would stop the A-Href being triggered.

Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)


This is a non-JQuery solution I just tested and it works.

<html lang="en">
<head>
<script type="text/javascript">
addEventListener("load",function(){
    var links= document.getElementsByTagName("a");
    for (var i=0;i<links.length;i++){
        links[i].addEventListener("click",function(e){
        alert("NOPE!, I won't take you there haha");
        //prevent event action
        e.preventDefault();
        })
    }
}); 

</script>
</head>
<body>
<div>
<ul>
    <li><a href="http://www.google.com">Google</a></li>
    <li><a href="http://www.facebook.com">Facebook</a></li>
    <p id="p1">Paragraph</p>
</ul>
</div>
<p>By Jefrey Bulla</p>
</body>
</html>

Yet another way of doing this in Javascript using inline onclick, IIFE, event and preventDefault():

<a href='#' onclick="(function(e){e.preventDefault();})(event)">Click Me</a>

after several operations, when the page should finally go to link you can do the following:

          jQuery("a").click(function(e){
            var self = jQuery(this);
            var href = self.attr('href');
            e.preventDefault();
            // needed operations

            window.location = href;
          });

Why not just do it in css?

Take out the 'href' attribute in your anchor tag

<ul class="product-info">
  <li>
    <a>YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

In your css,

  a{
    cursor: pointer;
    }

If stopping the propagation of the event doesn't bother you, just use

return false;

at the end of your handler. In jQuery it prevents the default behaviour and it stop the event bubbling.


You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.

Returning the event when it's called:

<a href="" onclick="return false;"> ... </a>

Void case:

<a href="javascript:void(0);"> ... </a>

You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?

참고URL : https://stackoverflow.com/questions/265478/preventdefault-on-an-a-tag

반응형