The function does not work in a separate function

I have some problems with jquery. If I provide my jQuery in a function, it fails.

function foo(){
        $(this).hide();
 }   
<input type='button' value='Button' onclick='foo()'>

I tried to fire the event inside onclick and it worked.

<input type='button' value='Button' onclick='$(this).hide()'>

I think the problem is the 'this' object, but I could not understand why.

+4
source share
4 answers

Try the following:

function foo(obj){
        $(obj).hide();
 }   
<input type='button' value='Button' onclick='foo(this)'>
+4
source

I will assume that the function lies on it with a script tag that is located at the end of the body (good guess?), Then try this one function foo(e){$(e.target).hide()}or use vanilla JS, because it's just even without jQuery (optimization): D

+1
source

hide() - jquery, jquery. jquery ?

function foo(){
     $(this).hide();
}
$("input[type=button]").click(foo); //set event handler

... onclick:

<input type='button' value='Button'>

:

function foo(){
     $(this).hide();
}
$(".button").click(foo);

... .

<input type='button' class='button' value='Button'>

API for jquery click: https://api.jquery.com/click/

+1
source

If you use jquery, you can directly bind the click event with a class or id

Note. you can use more than one button for an event, also see an example:

WHAT IS IT

$('.click').click(function(){

 $('h1').html($(this).attr('name'));

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click" name="one">one</button>
<button class="click" name="two">two</button>
<button class="click" name="three">three</button>
<button class="click" name="four">four</button>
<h1></h1>
Run code
0
source

Source: https://habr.com/ru/post/1616487/


All Articles