How i can change the class
of an HTML element (X:element) when i click on <a>
, and when i click on other elements (div,body,li), the class of this element (X:element) change This is the example:
<a class='A'></a>
<div class='click'></div>
When i click on a
addClass
( B )
When i click on other elements removeClass
:( B )
Try with following code:
$(document).ready(function(){ var aTag = $("aA"); var divTarget = $("div.click"); $(document).click(function(e){ var target = $(e.target); if(target.is(aTag)){ if(divTarget.hasClass("B")) divTarget.removeClass("B"); else divTarget.addClass("B"); } else if(!target.is(divTarget)) { $(divTarget).removeClass("B"); } }); })
.B{ color: blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <a class='A'>Link A</a> <div class='click'>Click Div</div> <div class='click1'>Click Div 1</div> <div class='click2'>Click Div 2</div>
As I understand you right, you talk about something like this:
$(document).on('click',function(){
$('.A').removeClass('B');
});
$('.A').on('click',function(e){
$('.A').addClass('B');
e.stopImmediatePropagation();
return false;
});
Assuming I understand your question, I add class B to .click if you click on A, clicking anywhere else, I remove it
$(function() { $(document).on("click", function(event) { var $tgt = $(event.target); $(".click").toggleClass("B", $tgt.hasClass('A')) }); });
.B { color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a class='A'>Click here</a> <div class='click'>Text</div>
If I understand you correctly, this should work...
$('.a').on('click', function(){
$(this).addClass('B');
});
$('.click').on('click', function(){
$('.a').removeClass('B');
});
Clicking on the 'a' tag will add the class B to the 'div' with the class click .
When anything but the 'div' with the class click is clicked the class B is removed.
$(document).ready(function() {
$(".A").on("click", function() {
$(".click").addClass("B");
return false; // prevents the page from being reloaded
});
$(document).on("click", function() {
if(!$(this).hasClass('click')) {
$(".click").removeClass("B");
}
return false;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.