Javascript JQuery 通过给定的 id 更改类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5553551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:46:28  来源:igfitidea点击:

JQuery change class by given id's

javascriptjquery

提问by Tom

I have a number of tables, for example:

我有很多表,例如:

<table class="onion" id="12">

When a div named "Mark_Pre_Val" gets clicked i want tables with the id's 4, 6, 12 & 21 to change their class to "onionClick", and if one of them is already "onionClick" then don't change the class.

当单击名为“Mark_Pre_Val”的 div 时,我希望 ID 为 4、6、12 和 21 的表将它们的类更改为“onionClick”,如果其中一个已经是“onionClick”,则不要更改类。

Here is the click event:

这是点击事件:

    $(".Mark_Pre_Val").click(function(){       });

Can someone point me to the right direction how to approach this?

有人可以指出我如何解决这个问题的正确方向吗?

回答by cantlin

$(".Mark_Pre_Val").click(function(){ 
  $('#4, #6, #12, #21').removeClass('onion').addClass('onionClick');
});

Edit: as others have pointed out, element ID's should not contain only numbers. If you are outputting these tables in a loop and using the ID as an iterator, you may find it more elegant to use index().

编辑:正如其他人所指出的,元素 ID 不应只包含数字。如果您在循环中输出这些表并使用 ID 作为迭代器,您可能会发现使用index()更优雅。

回答by Enrique Moreno Tent

Dont put ID's that start with number, please.

请不要输入以数字开头的 ID。


$(".Mark_Pre_Val").click(function(){
    $("#4, #6, #12, #21").removeClass("onion").addClass("onionClick");
});

回答by Code Maverick

$("#Mark_Pre_Val").click(function(){

    $("#4,#6,#12,#21")
        .not("onionClick")
        .removeClass("onion")
        .addClass("onionClick");

});

EDIT:

编辑:

None of the above answers are going to work as the click event will never be fired if you are selecting the class .Mark_Pre_Val. You said your div was named Mark_Pre_Val, so you need to use # when selecting. Also ... why not use not() to immediately filter those that don't have the class you want to change to, then remove the old class, and finally add the new class?

上述答案都不起作用,因为如果您选择类 .Mark_Pre_Val,则永远不会触发单击事件。你说你的div被命名为Mark_Pre_Val,所以你需要在选择时使用#。还有...为什么不使用not() 立即过滤那些没有您想要更改的类的那些,然后删除旧类,最后添加新类?

回答by Jeroen

$('#4, #6, #12, #21').toggleClass('onionClick');

$('#4, #6, #12, #21').toggleClass('onionClick');