Clicking anchor should execute javascript not go to new page

前端 未结 5 836
忘掉有多难
忘掉有多难 2021-01-14 07:45

I have a HTML anchor that when clicked should make a div slide up or down (I call JQuery\'s .slideToggle(); function);

My Problem: When

5条回答
  •  醉话见心
    2021-01-14 08:11

    I see a lot of answers that involve work-arounds, but none that hit the heart of the issue. The why behind what you're doing is not working, and why it often does work.

    You're using javascript:XXX as the value for the href, hypertext source link, attribute on your anchor tag. Where XXX is some piece of javascript code, an expression, such as a function call.

    When using this notation, the XXX code is first evaluated. If the expression results in a value, then most browsers will clear the page and display only the resultant value.

    For example,

    Click here! will result in 2 being displayed.

    Similarly, this could be rewritten with a function to produce the same results:

    function addTwo() {
        return 1+1; 
    }
    

    Click here! (expected output 2)

    For most browsers, if the XXX code is evaluated and does not result in a value, then it has nothing to display -- as such, it will stay on the same page. So, there's a few ways to achieve this behavior.

    • We could assign the result to a variable.

    Click here!

    There is no result left over during assignment.

    • We could wrap another function that does not return anything around this function.

    A.

    function addTwo2() {
        addTwo();
    }
    Click Here!
    

    B. Same thing, but all inline:

    Click Here!

    C. Same thing, but with the ! idiom you'll often see. (Same logical meaning, just uses the not operator to achieve less characters used):

    Click Here!

    • We could instead do what is referred to as hooking in most functional programming languages:

      function addTwo() {     
          alert( "sfsf" );
          return 1+1; 
      }
      
      var x = addTwo;
      
      addTwo = function() {
          x();    
      }
      

      Click Here!

    • Lastly, if your function or expression does not need to return anything, simply don't do it in that function.

    So in summary:

    When your anchor using a javascript: href is clicked, the javascript code after javascript: is first evaluated, if it results in a value the browser will display only the result, otherwise the browser will stay on the page it currently is on since it has no value to display.

提交回复
热议问题