JQuery beginner - a reference to an HTML object passed to a JS function

There seems to be a better way to code this:

HTML snippet:

<label onclick="addstuff(this)" id="label_id">Hello</label>

JS / jQuery snippet:

function addstuff(field){
    $('#'+field.id).before('<div>Just a random element being added…</div>');
}

I don't like the fact that I reference my field in Javascript to $ ('#' + field.id) when the field is already passed. It seems that in jQuery there should be another way of referencing a field in jQuery using a field, the object that is being passed, which, in my opinion, should be more efficient, but I will not be able to figure it out. Any advice is appreciated.

+3
source share
3 answers

This is an easier way.

$('#label_id').click(addstuff);

function addstuff(){
    $(this).before('<div>Just a random element being added…</div>');
}

this event. . event

function addstuff(event){
    $(event.target).before('<div>Just a random element being added…</div>');
}

inline

$('#label_id').click(function (){
    $(this).before('<div>Just a random element being added…</div>');
});

, . , .

DOM. ,

$(document).ready(function() { /* code here */ });

+2

:

$(function() {
   $('#label_id').click(function() {
       $(this).before('<div>Just a random element being added…</div>');
   });
});

label_id. Javascript this. jQuery, $(this). $ jQuery.

jQuery , onEvent HTML-. , HTML- :

<label id="label_id">Hello</label>

Javascript <script type="text/javascript"></script>.

" " $(function(){ /* code here */ }) , DOM. , , .

jQuery jQuery ;)

+2

"this":

function addstuff(field){
    $(this).before('<div>Just a random element being added…</div>');
}

jquery magic variable.

0
source

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


All Articles