在Wordpress中使用Jquery和CSS区分两个相同的HTML ID元素 [英] Distinguishing between two same HTML ID elements using Jquery and css in Wordpress
问题描述
我知道,拥有多个具有相同ID的HTML元素是一种不好的做法.但是在这种情况下,我需要专门修改它们中的任何一个.
I know that is a bad practice to have more than HTML elements having same ID. However such is my situation where I need to specifically modify either of them.
我已研究找到并找到关于 Jquery 方法'document.getElementByID',该方法与第一个相似元素一起返回并让您可以使用 css 对其进行更改.使用该代码,我在下面编写了代码,但是没有用.
I researched around and found about Jquery method 'document.getElementByID' that returns with the first similar element and lets you change it using css. Using that I wrote the code below but it doesn't work.
$(document.getElementById('it_trending-3')).css({"display":"none"});
我已使用 CSS-JS-PHP在我的wordpress主题中添加了此代码wordpress插件,从中创建了一个快捷方式,然后添加了简码.有人可以指导我哪里以及哪里出了问题吗?
I have added this code in my wordpress theme using the CSS-JS-PHP wordpress plugin, created a shortcut from the same and then added the shortcode. Can someone please guide me what and where I went wrong?
还可以随意提出一个不同的功能,该功能可能会让我使用也许索引专门指向每个相同的ID元素.谢谢!
Also feel free to suggest a different function that would maybe let me specifically point to each of the same ID elements using maybe indexes. Thanks!
推荐答案
将一个类保留在要更改的div上:
Keep a class to the divs you want to change:
<div>
<span id="a" class="test">1</span>
<span id="b" class="test">2</span>
<span>3</span>
</div>
Jquery会像这样:
The Jquery would go like this:
$(function() {
var w = $("div");
console.log($('#a').length);
console.log($('body #a').length);
console.log($('#a', w).length);
});
$(".test").first().css({"color":"orange"});
//or
$(".test:first").css({"color":"orange"});
但是,如果您想通过各种索引选择类中的任何特定元素,则需要这样做:
But if you want to select any specific element with the class via an index of sorts, then you would need to do it like this:
var x = $(".test");
$(x[1]).css({"color":"orange"});
这篇关于在Wordpress中使用Jquery和CSS区分两个相同的HTML ID元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!