我试图根据count的值显示两个不同的代码位。
例如,如果count等于1,我想显示以下代码:
<h5>person has visited</h5>
如果它更多,我想显示
<h5>people have visited</h5>
这是我目前的代码:
<h5 class="visitor-count count">{{ $place->visitors->count()}}</h5>
<h5 class="visitor-count count-text">people have visited</h5>
$('.visit').on('click', function(event){
event.preventDefault();
var buttonToChange = $(this);
var $this = $(this);
$.ajax({})
.done(function() {
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Visited?');
count = $this.siblings('.count');
count.html(parseInt(count.html()) - 1);
} else {
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html("I've Visited <i class='fas fa-check'>");
count = $this.siblings('.count');
count.html(parseInt(count.html()) +1);
}
});
});
答案 0 :(得分:1)
我不确定你在这里尝试做什么,但是:
count
变量,该变量未被声明。 例如,如果count等于1,我想显示以下代码:
<h5>person has visited</h5>
它的行为方式是否符合您的要求?
$('.visit').on('click', function(event) {
event.preventDefault();
var buttonToChange = $(this);
var $this = $(this);
var count;
$.ajax('http://www.google.fr')
.done(function() {
if (buttonToChange.hasClass('btn-visited')) {
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Visited?');
count = $this.siblings('.count');
count.html(parseInt(count.html()) - 1);
} else {
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html("I've Visited <i class='fas fa-check'>");
count = $this.siblings('.count');
count.html(parseInt(count.html()) + 1);
}
// simple if / else to change the text in 'count-text' depending on the value of 'count'
if (parseInt(count.html()) === 1) {
$(".count-text").html("person has visited");
} else {
$(".count-text").html("people has visited");
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="visit btn-visited">Visit</button>
<h5 class="visitor-count count">2</h5>
<h5 class="visitor-count count-text">people have visited </h5>
&#13;