简体   繁体   English

使用jQuery影响具有相同ID的div

[英]Using jquery to affect divs with same id

I have more than 1 div with the same id, and I'm trying to use jquery to affect all of them at the same time, as oppose to just the first div. 我有1个以上具有相同ID的div,并且我尝试使用jquery同时影响所有这些div,与仅第一个div相反。 Is there a way to do this without changing the div id? 有没有一种方法可以不更改div ID?

<div id = '1'>
<div id = '1'>
<div id = '1'>

//codes
document.getElementById(1).innerHTML = data;
$("#"+1).hide();
$("#"+1).fadeIn(500);
//codes

id is supposed to be unique. id应该是唯一的。 Instead use a class. 而是使用一个类。

 $( document ).ready(function() { $(".fader").html("testing"); $(".fader").hide(); $(".fader").fadeIn(500); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="fader">test</div> <div class="fader">test</div> <div class="fader">test</div> 

In HTML, the id attribute should be unique throughout the entire document. 在HTML中,id属性在整个文档中应该是唯一的。 There should never be 2 elements having the same id attribute value. 绝对不能有2个元素具有相同的id属性值。

What you need to do is use a class, which can be used on many elements throughout the html document. 您需要做的是使用一个类,该类可以在整个html文档的许多元素上使用。

<div class="theClassName"></div>
<div class="theClassName"></div>
<div class="theClassName"></div>

var elementsArray = document.getElementsByClassName("theClassName");
for(var i = 0; i < elementsArray.length; i++) {
    var element = elementsArray[i];
    // do something with each element
}

Using Attr selector can resolve your problem. 使用Attr selector可以解决您的问题。

$('[id='1']')

But that is very not recommend, because the id attr is design to be unique.Instead of that, you can use class or name attr. 但这是不建议的,因为id attr是设计为唯一的,您可以使用classname attr来代替。

<div class='someClass' name='someName'>
<div class='someClass'>
<div class='someClass'>

// using class
$('.someClass').hide();

// using name
$('div[name='someName']').hide();

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

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