gpt4 book ai didi

javascript - jQuery:根据 if/else 结果更改每个
中的每个

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:44 25 4
gpt4 key购买 nike

在我的 HTML 中,我有一个画廊,其中每个画廊元素都具有以下格式:

<div class="gallery-img">
<a href="#" target="_blank">
<img src="#" />
</a>
<p class="imgDescription">November 20th</p>
<span class="hidden">20141120</span>
</div>

我目前正在尝试构建一个函数,该函数将根据隐藏的 <span> 之间的差异为每个 .imgDescription 分配不同的字符串。和一个外部 today保存当前日期的变量。这是 JS/jQuery:

today = yyyy+mm+dd;

$('.gallery-img').each(function() {
var itemRelease = $('.gallery-img span');
var timeToRelease = itemRelease - today;

if(timeToRelease < -1) {
$('.imgDescription').val(timeToRelease + " " + "days ago.");
} else if(timeToRelease > +1) {
$(this).val("In" + " " + timeToRelease + " " + "days");
} else if(timeToRelease === -1) {
$(this).val("Released yesterday");
} else if(timeToRelease === 1) {
$(this).val("Releases tomorrow");
} else if(timeToRelease === 0) {
$(this).val("Releases today!");
}
});

我将如何让 jQuery 比较每个 <div><span>值,然后将结果案例插入相应的 .imgDescription?

today 的内容变量在代码的前面定义。我使用 if/else 而不是 switch,因为之前的线程表明 switch 会慢 30 倍。

完全卡在这个上面!帮助将不胜感激:)

最佳答案

你应该比较每个 .gallery-img

// wrap in document ready
$(function() {

var today = new Date();
var dd = today.getDate();
var mm = (today.getMonth()+1) * 100; //January is 0! *100 to form single number
var yyyy = today.getFullYear() * 10000; // *10000 to form single number

today = yyyy+mm+dd;
var todayString = today.toString();

$('.gallery-img').each(function() {

var $this = $(this);
var itemRelease = $this.find('span');
var imgDescription = $this.find('.imgDescription');
var timeToRelease = campareDate(toDate(todayString), toDate(itemRelease.text()));

console.log(timeToRelease);

if(timeToRelease > 1) {
imgDescription.text(timeToRelease + " " + "days ago.");
} else if(timeToRelease < -1) {
imgDescription.text("In" + " " + -timeToRelease + " " + "days");
} else if(timeToRelease === 1) {
imgDescription.text("Released yesterday");
} else if(timeToRelease === -1) {
imgDescription.text("Releases tomorrow");
} else if(timeToRelease === 0) {
imgDescription.text("Releases today!");
}
});

});

function toDate(str) {
return new Date(str.substr(0,4) + '-' + str.substr(4, 2) + '-' + str.substr(6, 2));
}

function campareDate(date1, date2) {
return Math.floor((date1 - date2) / (86400 * 1000));
}

演示:

http://jsfiddle.net/70nzrgxy/1/

关于javascript - jQuery:根据 if/else 结果更改每个 <div> 中的每个 <p>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com