jQuery:是否可以在单击时更改无ID/无类元素
jQuery: is it possible to make ID/class-less elements change on click?
示例 css:
div {
background-color: green;
}
示例 html:
<div>apple 1</div>
<div>apple 2</div>
<div>apple 3</div>
是否可以将 jquery 点击绑定到这些,以便点击的div 将背景颜色更改为蓝色,而其他的将恢复为默认颜色?
我在想这样的事情:
$("div").click(function() {
// first change all to default color
$("div").each( background-color: green; }
// then change the clicked div to blue
how to get the clicked element in here I dont know.
});
使用 $(this)
来引用单击的元素:
$("div").click(function() {
// first change all to default color
$("div").css('background-color', 'green')
// then change the clicked div to blue
$(this).css('background-color','blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>Apple 1</div>
<div>Apple 2</div>
<div>Apple 2</div>
延伸阅读:
JQuery的这个:揭秘 - 雷米夏普
使用这个
$("div").click(function() {
// first change all to default color
$('div').css( 'background-color', 'green');
$(this).css( 'background-color', 'blue');
alert($(this).text());
});
单击的元素将被$(this)
,因此$(this).css("background-color", "green");
将为单击的元素着色,$("div").removeAttr("style")
将从其余元素中删除所有定义的颜色。
所以:
$("div").click(function() {
// remove the style attribute from every 'div' element to reset it to the value defined in CSS
$("div").removeAttribute("style");
// use $(this) to apply the color the clicked element itself
$(this).css({"background-color": "green"});
});
相关文章:
- Javascript:表单验证getElementById仅返回第一个id元素
- 如何为每个带有数字的id元素使用Javascript函数
- 使用regex选择ID元素
- Bootstrap Navbar在选择ID元素后未折叠
- JavaScript-更改一组包含特定文本和变量ID元素的链接
- 父页面中的 JQuery 未在部分视图中检测到 id 元素
- ID 元素在作为参数给出时返回
- 当 Javascript 中的 POST ID 元素插入 PDO 时,数据库中没有结果
- 为什么变量值不显示在 id 元素中
- 如何查找 id 元素的文本值
- 使用 ajax 将 id 元素传递给数据库
- 从另一个HTML文件中获取ID元素
- 正在克隆html标记id元素
- 如何在html中循环使用ID元素
- 获取动态生成的id元素的内部文本发送到谷歌分析
- 如何通过tagname检查ID元素
- jQuery滚动到底部的ID元素
- 检查Id元素javascript
- 在我显示一个id元素后,页面跳转到顶部
- 如何在HTML中突出显示当前的id元素