问题
I've got some p
tags with the class PointsToggle
<p class="PointsToggle">POINTS STATEMENT - AVAILABLE 7AM TOMORROW</p>
<p class="PointsToggle">SOME OTHER TEXT</p>
And some jQuery like this
$('.PointsToggle').each(function() {
if ($(this).text = 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
$(this).css('width', '510px');
}
else {
$(this).css('width', '20px');
}
})
But I can't seem to get it to work
Any ideas?
Thanks
Jamie
回答1:
$('.PointsToggle').each(function() {
var $this = $(this);
if ($this.text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
$this.width(510);
} else {
$this.width(20);
}
})
回答2:
You are using = which means assign. Try == instead.
回答3:
.text() is a function, so you're missing some parenthesis when calling it, like this:
if ($(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
Or a bit simpler overall in jQuery 1.4+:
$('.PointsToggle').width(function() {
return $(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW' ? 510 : 20;
});
回答4:
This will work:
$('.PointsToggle').each(function() {
if ($(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
$(this).css('width', '510px');
}
else {
$(this).css('width', '20px');
}
})
回答5:
$(document).ready() {
$('.PointsToggle').each(function() {
if($(this).html() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
$(this).width(510);
} else {
$(this).width(20);
}
})
});
EDIT:
If it's possible I would have the code generating the html add another class. Then this can all be done with css. For example:
<p class="PointsToggle Toggled">POINTS STATEMENT - AVAILABLE 7AM TOMORROW</p>
<style>
.PointsToggle {width:20px;}
.PointsToggle.Toggled {width:510px;}
</style>
来源:https://stackoverflow.com/questions/3922887/jquery-each-function-not-working