问题
I'm just doing test scenarios trying to understand jquery a little more. I understand that what I'm trying to do won't work and I'm sure I could look up a more complicated solution involving toggle or something but I'd like to know the logic behind why this wont work...
I would like to have a button that when pressed inserts text. When it is pressed again it inserts a different set of text. I'm trying to play with the whole adding/removing classes thing so I'm trying to add class 'text1' to my textarea div. I then go on and create another click function that tries to select that 'text1' class that I just added and insert HTML again.
If I have the 'textarea.text1' selector below my 'textarea' (as shown in my example) selector it understandably goes through and adds the text1 class and then finds it and immediately enters the "Text Content 2"
I thought by having the 'textarea.text1' selector above it would move past the first .click without doing anything and then add the class. This doesn't seem to work...
I then expected to click on the ChangeText button again and have it find the class in the first part of my script.....
Can anyone explain why this isn't working and the simplest method to accomplish this?
Thanks in advance.
Javascript:
$(document).ready(function() {
$('.changetext').click(function() {
$('.textarea').html('<p> Text Content 1</p>').addClass('text1');
});
$('.changetext').click(function() {
$('.textarea.text1').html('<p> Text Content 2</p>');
});
});
HTML:
<body>
<div class="textarea"></div>
<button class="changetext">ChangeText</button>
</body>
Jfiddle: http://jsfiddle.net/nlaffey/qzKJx/1/
回答1:
It is not very clear what you are trying to do. I think you know you are double binding the click event. I think the underlying question is how to cycle through some text and classes by clicking a button.
$(document).ready(function () {
var $ta = $('.textarea'),
text = ['Text Content 1', 'Text Content 2', 'Text Content 3'];
$('.textarea').data('textindex', -1);
function rotateText(){
var cls = $ta.prop('class'),
idx = $ta.data('textindex'),
maxidx = text.length;
if (idx++ == maxidx - 1) idx = 0;
while(maxidx--){
$ta.removeClass('text' + maxidx );
}
$ta.html(text[idx]).addClass('text' + (idx))
.data('textindex', idx);
}
$('.changetext').click(rotateText);
});
http://jsfiddle.net/bxQ5r/
回答2:
Why you are using multiple click events for single button, you can do this
$('.changetext').click(function () {
if(!$('.textarea').hasClass('text1'))
{
$('.textarea').html('<p> Text Content 1</p>').addClass('text1');
}
else
{
$('.textarea').removeClass('text1');
$('.textarea.text1').html('<p> Text Content 2</p>');
}
});
see here Fiddler code
来源:https://stackoverflow.com/questions/16870303/adding-class-onclick-and-then-selecting-by-that-class-on-next-click