如何使用JS为除特定图像之外的所有图像添加类

时间:2018-04-10 13:00:21

标签: javascript jquery

我想为所有图像添加一个类,除了两个特定图像。因为我不想将该类添加到徽标中。

这就是我现在所拥有的:

$('img').addClass('class_two');

我想要添加此课程的图片是:

<img id="id_1" src="danielgotzlogo.png" alt="danielgotzlogo">
<img id="id_2" src="xxsbanner.jpg" alt="#">

但是这会将它添加到所有图像中。我怎么能不把类添加到特定的类?

3 个答案:

答案 0 :(得分:2)

考虑到您不想影响的两个元素的特定ID:

$('img').not('#id1').not('#id2').addClass('myclass');

或:

$('img').not('#id1,#id2').addClass('myclass');

或:

$('img:not(#id1,#id2)').addClass('myclass');

答案 1 :(得分:1)

尝试以下方法:

import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import axios from 'axios'; class LogoutPage extends Component { constructor(props) { super(props); this.state = { navigate: false } } componentDidMount(e) { axios.get('http://localhost:3016/logout') .then( this.setState({ navigate: true }), ) .catch(err => { console.error(err); }); if (this.state.navigate) { setTimeout(() => { return <Redirect to="/employers" /> }, 2000); } }; render() { if (this.state.navigate) { setTimeout(() => { return <Redirect to="/employers" /> }, 2000); } return ( <div>You successfully logouted</div> ) } } export default LogoutPage;

如果您的徽标(您不想在其上添加课程)具有班级$("img:not(#id_1,#id_2)").addClass("class_two");,那么您可以尝试以下操作:

logo

答案 2 :(得分:1)

你可以写一个这样的函数:

function _addClass(klass, to, except){
    $(to).not(except.join()).addClass(klass)
}

_addClass('class_two', 'img', ['#id_1', '#id_1'])

除了那些匹配'except'选择器的那些元素之外,这会将'klass'类添加到'to'的每个元素中。

演示:https://jsfiddle.net/xpvt214o/89314/