Why can't I call a function named clear from an onclick attribute?

后端 未结 2 967
迷失自我
迷失自我 2020-11-22 01:27

i\'m trying to create a simple calculator, when a button is clicked its value is shown in the text field and the button \"C\" should clear the text field but its onclick=\"

2条回答
  •  遥遥无期
    2020-11-22 02:05

    Intrinsic event attributes (like onclick) are horrible. Internally they implement with:

    Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues.

    Consequently, you are actually calling document.clear() instead of your global clear().

    The quick fix for this is to rename the function to something else or explicitly call window.clear().

    The better solution is to bind your event handlers with addEventListener instead of intrinsic event attributes.

提交回复
热议问题