这里thisid存储html元素的id。 我想用下面的代码更改它的背景颜色
null
let thisid = 'test';
$("a#" + thisid).css("background-color", "yellow");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="test" href="#">Hello world!</a><br/>
<a id="test2" href="#">Goodbye all</a>
null
这是不起作用的,但如果我删除这个ID并按以下方式编写它,它就会起作用
$("a").css("background-color","yellow");
但它选择所有带有标记的
下面是我真正想做的。
$(document).ready(function() {
// hide all questions
$("h1").hide();
// display first question
$("h1#1").show();
// show selected question
$("a").bind('click',function(){
let thisid = $(this).attr('id');
$("h1").hide();
$("h1#"+thisid).show();
$("a#"+thisid).css("background-color","yellow");
});
});
jQuery函数的参数($()
)被视为CSS选择器。 由于您试图通过ID查找元素,因此需要用一个OPTHORPE(#
)启动选择器。 以字符开始,按标记类型选择。 由于html不方便,我猜实际问题是ID为thisid
的元素不是标记。 (您实际上选择的是“Any a tag with id
thisid
”,但由于id是唯一的,包括标记类型选择器是多余的)
您应该能够做更像这样的事情:
null
let thisid = "two"
$("#"+thisid).css("background-color","yellow");
thisid = "three"
// won't work, element with id `three` is not an 'a' tag
$("a#"+thisid).css("background-color","green");
thisid = "four"
$("div#"+thisid).css("background-color","blue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>