给定一个HTML文档, 任务是使用JQuery同时选择具有不同ID的元素。
方法:
- 选择其他元素的ID, 然后使用each()方法将CSS属性应用于所有选定ID的元素。
- 然后使用css()方法将所有选定元素的背景色设置为粉红色。
- 显示指示多个ID选择器的文本。
范例1:在此示例中, 选择了具有不同ID的元素, 并更改了这些元素的背景颜色。
<!DOCTYPE HTML>
< html >
< head >
< title >
JQuery | Multiple ID selectors
</ title >
< style >
#GFG_DIV {
background: green;
height: 100px;
width: 200px;
margin: 0 auto;
color: white;
}
</ style >
< script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" >
</ script >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
lsbin
</ h1 >
< p id = "GFG_UP" style =
"font-size: 19px; font-weight: bold;" >
</ p >
< div id = "GFG_DIV" >
This is Div box.
</ div >
< br >
< button onClick = "GFG_Fun()" >
click here
</ button >
< p id = "GFG_DOWN" style =
"color: green; font-size: 24px; font-weight: bold;" >
</ p >
< script >
$('#GFG_UP').text("Click on button to select multiple"
+ " ID's and change their background-color");
function GFG_Fun() {
$("#GFG_UP, #GFG_DIV, #GFG_DOWN").each(function(){
$(this).css("background-color", "pink");
});
$('#GFG_DOWN').text("Background-color of all "
+ "elements is changed.");
}
</ script >
</ body >
</ html >
输出如下:
在单击按钮之前:
单击按钮后:
范例2:在此示例中, 选择了具有不同ID的元素, 并且更改了这些元素的文本颜色。
<!DOCTYPE HTML>
< html >
< head >
< title >
JQuery | Multiple ID selectors
</ title >
< style >
#GFG_DIV {
background: green;
height: 100px;
width: 200px;
margin: 0 auto;
color: white;
}
</ style >
< script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" >
</ script >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
lsbin
</ h1 >
< p id = "GFG_UP" style =
"font-size: 19px; font-weight: bold;" >
</ p >
< div id = "GFG_DIV" >
This is Div box.
</ div >
< br >
< button onClick = "GFG_Fun()" >
click here
</ button >
< p id = "GFG_DOWN" style =
"color: green; font-size: 24px; font-weight: bold;" >
</ p >
< script >
$('#GFG_UP').text("Click on button to select multiple"
+ "ID's and change their Text color");
function GFG_Fun() {
$("#GFG_UP, #GFG_DIV, #GFG_DOWN").each(function(){
$(this).css("color", "blue");
});
$('#GFG_DOWN').text("Text color of all elements is "
+ "changed.");
}
</ script >
</ body >
</ html >
输出如下:
在单击按钮之前:
单击按钮后: