Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: add click event to specific id

I have a small jquery problem:

My code is like this:

<div id="select-word-5" class="select-word-link"> - some content - </div>
<div id="select-5" class="select"> - some content - </div>

I have throughout my document several select-word-link and select divs.

I want to add a click event to the first div, that reacts just to the second div.

My idea was to loop through all the "select-x" elements, but i think there is a much better way?

$('.select-word-link').each(function()
{

    var id = this.id;
    var idLink = this.id.replace("-word", "");


    $('.select').each(function()
    {

        if (idLink == this.id)
        {


          $(id).click(function() {
            alert("this does not work");

        });

    });


});
like image 297
mangotasche Avatar asked Feb 07 '16 10:02

mangotasche


2 Answers

You can do this easier by triggering an action on an event.

$('#select-5').click(function(){
    alert('Does this work?');
});

$('.select-word-link').click(function(){
    $('#select-5').trigger('click'); // will behave as if #select-5 is clicked.
});

Info: http://api.jquery.com/trigger/

More advanced:

$('#select-5').click(function(){
    alert('Does this work?');
});

$('#select-6').click(function(){
    alert('Does this work?');
});

// etc

$('.select-word-link').click(function(){
    var selectId  = this.id.replace('-word', '');
    $('#'+selectId).trigger('click'); // will behave as if #select-5 is clicked.
});
like image 199
Bob van Luijt Avatar answered Sep 30 '22 03:09

Bob van Luijt


maybe this code help you

    $(".select-word-link").click(function(){
    $(this).next().hide();
});

});

like image 33
morteza hosseini Avatar answered Sep 30 '22 03:09

morteza hosseini