我是新手使用jquery,并想知道如何附加并使用click事件从div中删除ID并附加到html.在下面的代码中,我已经能够通过单击div来附加ID,但我不知道如何删除.无论哪个div突出显示黄色都应该是附加的.再次单击div以删除突出显示也应该从html中删除ID.在此先感谢您的帮助.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('div.click').click(function() {
var bg = $(this).css('backgroundColor');
$(this).css({backgroundColor: bg == 'yellow' || bg == 'rgb(255, 204, 204)' ? 'transparent' : 'yellow'});
});
});
$(function( ){
$('#div1').bind('click', click);
$('#div2').bind('click', click);
$('#div3').bind('click', click);
});
function click(event){
$('#p1').append(event.target.id + ",");
}
</script>
</head>
<body>
<div class="click" id="div1">click me</div>
<div class="click" id="div2">click me</div>
<div class="click" id="div3">click me</div>
<p id="p1"></p>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
使用CSS类而不是直接更改样式有点干净.这样你就可以利用方便的toggleClass功能打开和关闭高亮显示.测试div是否突出显示也很容易:div.is(".highlighted")或者div.hasClass("highlighted")会告诉你.
<script type="text/javascript">
$(document).ready(function() {
$('div.click').click(function() {
$(this).toggleClass('highlighted');
});
});
$(function() {
// Can use one CSS selector to find all three divs and bind them all at once.
$('#div1, #div2, #div3').bind('click', click);
});
function click() {
var p1 = $("#p1");
if ($(this).is(".highlighted")) {
p1.append(this.id + ",");
}
else {
p1.text(p1.text().replace(this.id + ",", ""));
}
}
</script>
<style type="text/css">
.highlighted {
background: yellow;
}
</style>
Run Code Online (Sandbox Code Playgroud)