简体   繁体   English

使用Jquery动态添加类?

[英]Add the Class Dynamically using Jquery?

How can i add the class selectors dynamically to the img tag. 如何将类选择器动态添加到img标签。 For Example: img tag should be inside the anchor tag then only the class name:sample should add dynamically whichever anchor tag contain img like, Before: 例如:img标签应该在锚标签内,然后只有类名:sample应该动态添加包含img的锚标签,例如, 之前:

<a href="image.png"><img src="image.png"/></a>

After: 后:

<a href="image.png"><img src="image.png" class="sample"/></a>

If already image tag contain class then remove that class and the new class is possible in jquery. 如果图像标签已经包含类,则删除该类,并在jquery中添加新类。 I am not sure, how can i do this in jQuery. 我不确定,如何在jQuery中做到这一点。 Any suggestion would be great. 任何建议都很好。

Thanks, vicky 谢谢,vicky

You just need to toggle your class. 您只需要切换课程即可。 To do this, see: 为此,请参见:

$("img").toggleClass("border");

I made an example for you on CodePen. 我在CodePen上为您提供了一个示例。 Just click here . 只需单击此处

$(document).ready(function(){
$('your selector').addClass('sample'); //It can be select,img,a,etc.. });

Be specific in your tag for choosing. 在您的标签中要具体选择。 I use in CakePHP 3.x Date HtmlHelper field and it worked like a magic. 我在CakePHP 3.x Date HtmlHelper字段中使用它,就像魔术一样。

if($('a[href=image.png] > img').hasClass('sample')){
    $('a[href=image.png] > img').removeClass('sample');
}

And addClass for else part. addClasselse部分。

This can be done easily via jQuery.addClass and jQuery.removeClass APIs.. 这可以通过jQuery.addClass和jQuery.removeClass API轻松完成。

Add Class - http://api.jquery.com/addClass/ Remove Class - http://api.jquery.com/removeClass/ 添加类-http://api.jquery.com/addClass/删除类-http://api.jquery.com/removeClass/

应该这样做:

$('a img').removeClass().addClass('example')
$(document).ready(function(){
    $('a >img').addClass('sample'); //direct descendant of a
});

HTML code: HTML代码:

<img id="testImg" src="xyz.jpg" />

css code: CSS代码:

.displayNone{ display:none; }

jquery - to add class jQuery-添加类

`$("#testImg").addClass("displayNone");`

jquery - to remove class jQuery-删除类

$("#testImg").removeClass("displayNone");

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

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