简体   繁体   English

.addClass()在for()jQuery中不起作用

[英].addClass() not working inside for() jQuery

UPDATE - FINAL SOLUTION 更新-最终解决方案

Thank you to EVERYONE who has helped me with this problem. 谢谢所有帮助我解决此问题的人。 Special thanks must go to @Pranav for all of their help through email . 必须特别感谢@Pranav通过电子邮件提供的所有帮助 All of your answers seemed to have worked in JSFiddle yet I could not replicate it on my local server. 您的所有答案似乎都在JSFiddle中起作用,但我无法在本地服务器上复制它。

My problem was that my js file was firing before PHP had finished adding elements and classes dynamically. 我的问题是我的js文件在PHP完成动态添加元素和类之前就被触发了。 I was able to fix this (without using an event handler) with calling: 我能够通过调用来解决此问题(不使用事件处理程序):

( function() {
    jQuery(window).load( function($) {

// Add stuff

});
})(jQuery);

This seems to wait until PHP has done its thang and then fire. 这似乎要等到PHP完成了thang然后执行。 I can see the changes happen in the DevTools panel. 我可以在DevTools面板中看到更改。

I also didn't realise that Wordpress really doesn't seem to like $ and would rather have jQuery, so had to create $ = jQuery variable to counter this. 我也没有意识到Wordpress确实似乎并不喜欢$,而是希望使用jQuery,因此不得不创建$ = jQuery变量来解决这一问题。

Once again, thank you all. 再次感谢大家。 I have only just started learning jQuery and Javascript and this has been a great lesson to learn. 我才刚刚开始学习jQuery和Javascript,这是一个很棒的课程。


ORIGINAL QUESTION 原始问题

I am trying to add classes to a select boxes options depending on the classes they have been given by WooCommerce. 我试图将类添加到选择框选项,具体取决于WooCommerce提供的类。 (The reason for this is that I gave up trying to point to the 'disabled' property I couldn't get working.) (这样做的原因是,我放弃了尝试指向无法工作的“禁用”属性。)

For some reason, the code I am using isn't adding any classes. 由于某种原因,我正在使用的代码未添加任何类。

 jQuery(document).ready( function($) { // Classes for the link and the visible dropdown $selectclass='turnintodropdown'; // class to identify selects $listclass='turnintoselect'; // class to identify ULs $boxclass='dropcontainer'; // parent element $triggeron='activetrigger'; // class for the active trigger link $triggeroff='trigger'; // class for the inactive trigger link $dropdownclosed='dropdownhidden'; // closed dropdown $dropdownopen='dropdownvisible'; // open dropdown $i=0; $count=0; $sels=$('select'); $opts=$('option'); $trigger=('<a href="#"></a>'); function $switchTriggerClass (){ $($trigger).toggleClass($triggeron).toggleClass($triggeroff); } for($i; $i<$opts.length; $i++){ if($($opts).hasClass('enabled')){ $(this).addClass('woo'); } else { $(this).addClass('foo'); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <tbody> <tr> <td class="label"> <label for="size">Size</label> </td> <td class="value"> <select id="size" class="turnintodropdown" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"> <option value="">- -</option> <option value="10" class="attached enabled">10</option> <option value="20" class="attached enabled">20</option> <option value="30" class="attached enabled">30</option> <option value="40" class="attached enabled">40</option> <option value="50" class="attached" disabled="">50</option> <option value="60" class="attached" disabled="">60</option> </select> <a class="reset_variations" href="#" style="visibility: hidden;"></a> </td> </tr> </tbody> 

Any help would be greatly appreciated. 任何帮助将不胜感激。

Regards Michael 问候迈克尔

EDIT Hi all, 编辑大家好

I have tried all of these methods and the result is 'foo' being outputted to all option elements. 我已经尝试了所有这些方法,结果是将'foo'输出到所有选项元素。 I have also tried these methods on my navigation menu and the li elements are responding how I would expect this code to run. 我还在导航菜单上尝试了这些方法,并且li元素正在响应我希望该代码运行的方式。

My only conclusion has to be that Javascript/jQuery is not seeing the class 'enabled' even though it is definitely attached. 我唯一的结论是,尽管Javascript / jQuery确实已附加,但它并未看到“已启用”的类。

Could it be that the script is running before PHP has completed it processing? 脚本可能在PHP完成处理之前就已在运行吗? This is a dynamically loaded select box. 这是一个动态加载的选择框。

Cheers 干杯

Inside for loop this not refers to the element it may be window object or something else. 在for循环内部, this不是指可能是window对象或其他东西的元素。 Yo can resolve the problem using eq() method. 您可以使用eq()方法解决该问题。

for(; $i < $opts.length; $i++){
    // cache the element reference
    var $item = $opts.eq($i);
    // or $($opts[$i])

    if($item .hasClass('enabled')){
        $item .addClass('woo');
    }
    else {
        $item .addClass('foo');
    }
}

 var $opts = $('option'); for (var $i = 0; $i < $opts.length; $i++) { // cache the element reference var $item = $opts.eq($i); // or $($opts[$i]) if ($item.hasClass('enabled')) { $item.addClass('woo'); } else { $item.addClass('foo'); } } 
 .foo { color: red } .woo { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="size" class="turnintodropdown" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"> <option value="">- -</option> <option value="10" class="attached enabled">10</option> <option value="20" class="attached enabled">20</option> <option value="30" class="attached enabled">30</option> <option value="40" class="attached enabled">40</option> <option value="50" class="attached" disabled="">50</option> <option value="60" class="attached" disabled="">60</option> </select> 

Or using each() method instead of for loop 或使用each()方法代替for循环

$opts.each(function(){
    // cache the element reference
    $item = $(this);

    if($item .hasClass('enabled')){
        $item .addClass('woo');
    }
    else {
        $item .addClass('foo');
    }
});

 var $opts = $('option'); $opts.each(function() { // cache the element reference $item = $(this); if ($item.hasClass('enabled')) { $item.addClass('woo'); } else { $item.addClass('foo'); } }); 
 .foo { color: red } .woo { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="size" class="turnintodropdown" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"> <option value="">- -</option> <option value="10" class="attached enabled">10</option> <option value="20" class="attached enabled">20</option> <option value="30" class="attached enabled">30</option> <option value="40" class="attached enabled">40</option> <option value="50" class="attached" disabled="">50</option> <option value="60" class="attached" disabled="">60</option> </select> 


Even you can do it in 2 lines using filter() and not() methods. 甚至可以使用filter()not()方法分两行完成。

// filter all elements with the class and add the class
$opts.filter('.enabled').addClass('woo');      

// filter all elements which doesn't have the class and add the class
$opts.not('.enabled').addClass('foo');

 var $opts = $('option'); // filter all elements with the class and add the class $opts.filter('.enabled').addClass('woo'); // filter all elements which doesn't have the class and add the class $opts.not('.enabled').addClass('foo'); 
 .foo { color: red } .woo { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="size" class="turnintodropdown" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"> <option value="">- -</option> <option value="10" class="attached enabled">10</option> <option value="20" class="attached enabled">20</option> <option value="30" class="attached enabled">30</option> <option value="40" class="attached enabled">40</option> <option value="50" class="attached" disabled="">50</option> <option value="60" class="attached" disabled="">60</option> </select> 

The same with a single line using end() method. 与使用end()方法的一行相同。

$opts
   .filter('.enabled').addClass('woo')
   // back to the previous element object
   .end()
   .not('.enabled').addClass('foo');

 var $opts = $('option'); // filter all elements with the class and add the class $opts.filter('.enabled').addClass('woo') .end() .not('.enabled').addClass('foo'); 
 .foo { color: red } .woo { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="size" class="turnintodropdown" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"> <option value="">- -</option> <option value="10" class="attached enabled">10</option> <option value="20" class="attached enabled">20</option> <option value="30" class="attached enabled">30</option> <option value="40" class="attached enabled">40</option> <option value="50" class="attached" disabled="">50</option> <option value="60" class="attached" disabled="">60</option> </select> 

You have to change your code block from 您必须将代码块从

for($i; $i<$opts.length; $i++){
        if($($opts).hasClass('enabled')){
            $(this).addClass('woo');
        }
        else {
            $(this).addClass('foo');
        }
    }

To

$opts.each(function(){
    if($(this).hasClass('enabled'))
    {
        $(this).addClass('woo');
    }
    else
    {
        $(this).addClass('foo');
    }
})

Another way of doing is : 另一种方法是:

$('option.enabled').addClass('woo');      
$opts.not('.enabled').addClass('foo');

If you need an alternative then you can use foreach 如果您需要替代方法,则可以使用foreach

$opts.each(function(){
        if(($(this)).hasClass('enabled')){
            $(this).addClass('woo');
        }
        else {
            $(this).addClass('foo');
        }
    })

Try this approach instead. 请尝试这种方法。

$sels.find('option').each(function() {
 if($(this).hasClass('enabled')) {
  $(this).addClass('woo');
 } else {
  $(this).addClass('foo');
 }
});

In side for loop this doesn't give you the current element in loop. 在for循环中, this不会给您当前循环中的元素。 you need to use $($opt[$i]).hasClass() inorder to access your options in select box. 您需要使用$($opt[$i]).hasClass()来访问选择框中的选项。

 jQuery(document).ready( function($) { // Classes for the link and the visible dropdown $selectclass='turnintodropdown'; // class to identify selects $listclass='turnintoselect'; // class to identify ULs $boxclass='dropcontainer'; // parent element $triggeron='activetrigger'; // class for the active trigger link $triggeroff='trigger'; // class for the inactive trigger link $dropdownclosed='dropdownhidden'; // closed dropdown $dropdownopen='dropdownvisible'; // open dropdown $i=0; $count=0; $sels=$('select'); $opts=$('option'); $trigger=('<a href="#"></a>'); function $switchTriggerClass (){ $($trigger).toggleClass($triggeron).toggleClass($triggeroff); } for($i; $i < $opts.length; $i++){ if($($opts[$i]).hasClass('enabled')){ $($opts[$i]).addClass('woo'); } else { $($opts[$i]).addClass('foo'); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <tbody> <tr> <td class="label"> <label for="size">Size</label> </td> <td class="value"> <select id="size" class="turnintodropdown" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"> <option value="">- -</option> <option value="10" class="attached enabled">10</option> <option value="20" class="attached enabled">20</option> <option value="30" class="attached enabled">30</option> <option value="40" class="attached enabled">40</option> <option value="50" class="attached" disabled="">50</option> <option value="60" class="attached" disabled="">60</option> </select> <a class="reset_variations" href="#" style="visibility: hidden;"></a> </td> </tr> </tbody> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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