简体   繁体   中英

jQuery select the function selector

I'm trying to achieve something inside a function, to actually access the parent selector.

Here is a small snippet of my HTML code:

<div class="module-row module-tab pull-right" id="modtab-sql_net">
    <img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>

<div id="tab-module-row-1">
</div>

<div class="module-row module-tab pull-right" id="modtab-sql_dss">
    <img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>

<div id="tab-module-row-2">
</div>

Here is the jQuery script I tried:

$('div[id^="modtab-"]').click(function(){
    $(this).next('div[id^="tab-module-row"]').toggle(function(){
        $(this).next('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
// The above line is incorrect. I need to change img attr for the class which is inside the div being clicked
    });
});

Now, I want to actually change the image icon from a "plus" to a "minus" (the filenames are kept such).

I need to change $(this).next('.modtab-toggle') in the code to something that can work.

Please do NOT suggest to simply access the class using $('.modtab-toggle') as I have multiple such div tags in the code. It won't work out that way.

Thanks for any help.

Try this:

$('div[id^="modtab-"]').click(function(){
   $(this).find('.modtab-toggle').attr("src", function(i, attr){
              var o = this.src.indexOf('plus') > -1 ? this.src.replace('plus', 'minus') : this.src.replace('minus', 'plus');
              return o;
          });
});

See the Demo @ Fiddle

try something like this

    $('div[id^="modtab-"]').click(function(){
        var $this = $(this);// clicked div
        $this.next('.tab-module-row').toggle(function(){
            $this.find('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
        });
    });

Note: you should use class instead of id because it should be unique

#tab-module-row -> .tab-module-row

EDITED ANSWER

$('div[id^="modtab-"]').click(function(){
    var $this = $(this);// clicked div
    $this.next('div[id^="tab-module-row"]').toggle(function(){
        var img = $this.find('.modtab-toggle'); // your image object
        // your condition to check which image to display will goes here.
    });
});

change $(this).next('.modtab-toggle') to $(this).find('.modtab-toggle') to make it work.

See find() docs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM