jQuery div 클릭 이벤트에서 추가 및 제거하는 방법
문제
jQuery를 처음 사용하고 클릭 이벤트를 사용하여 DIV에서 ID를 추가하고 제거하는 방법을 알고 싶습니다. 아래 코드에서 ID가 DIV를 클릭하지 못하게 할 수 있었지만 제거 방법을 잘 모르겠습니다. 어떤 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>
해결책
스타일링을 직접 변경하는 대신 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>
다른 팁
나는 다른 기능을 한 취급에서 별도의 블록으로 유지하는 것을 좋아합니다. 준비가 된 이벤트.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var divs = new Object();
function click(event){
var did=event.target.id;
if($("#"+did).css('backgroundColor') == 'yellow')
divs[did]=true;
else
divs[did]=false;
AppendText();
}
function AppendText(){
var txt="";
for(var x in divs)
if(divs[x]==true)
txt +=x+",";
$('#p1').html(txt);
}
</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'});
});
$('#div1').bind('click', divclick);
$('#div2').bind('click', divclick);
$('#div3').bind('click', divclick);
});
</script>
제휴하지 않습니다 StackOverflow