Is there a way stop bubble in javascript without “e” parameter?

限于喜欢 提交于 2019-12-24 01:47:08

问题


I have see a lot tutorial that tell me the way to prevent bubble is use "e" parameter

just like :

function(e){
    e.preventDefault()
}

but in some situation,the firebug tell me it is wrong with "e is not define"

so is there a way to stop the bubble without the parameter e?


回答1:


If you set an event handler by using an element attribute (say, <button onclick="myFunc()">) the argument list will be empty. You have to use <button onclick="myFunc(event)"> instead to pass the current event as an argument. No argument will be passed to the callback function by default.

event is a special variable in this case. When using <element onEVENT="code"> the browser creates a new script and a function with the FunctionBody "code". This function will then take one argument event, thus you can use this object in your own function/code (see w3c:ehca). Note that IE creates a global object event for every triggered event.

So pass event as an additional variable and use e.preventDefault() and e.stopPropagation. Note that return false; won't cancel the propagation in a click event.

Demonstrations:

  • Demonstration showing the arguments of the callback function when using jQuery, <element onclick=""> and HTMLElementObject.onclick.
  • return false; vs e.stopPropagation(); (spoiler: return false; fails.)

References:

  • W3C: DOM Level 3: stopPropagation
  • W3C: DOM Level 3: preventDefault
  • W3C: HTML5 Event handler content attribute:

    Using the script execution environment created above, create a function object (as defined in ECMAScript edition 5 section 13.2 Creating Function Objects), with:

    Parameter list FormalParameterList

    If the attribute is the onerror attribute of the Window object

    • Let the function have three arguments, named event, source, and fileno.

    Otherwise

    • Let the function have a single argument called event.


来源:https://stackoverflow.com/questions/9766232/is-there-a-way-stop-bubble-in-javascript-without-e-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!