我有这个脚本,我需要它与onclick“按钮”更改图像从默认到第二个,并添加一个计数器/中断当它运行时,更改图像到第三个图像,当再次点击再次返回到第二个图像,并重新启动计时器。它需要保存在本地存储中,应该没问题。到目前为止,我找到了一些帮助,但现在我无法让它在onclick按钮上更改我的img src。有人能帮上忙吗?
$(document).ready(function() {
function aktivereSkift(initImagePath = null, initNextImagePath = null, count = 5) {
if (initImagePath === null || initNextImagePath === null) {
return false;
}
$(this).attr("src", initImagePath);
let timer = count * 1000;
let counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
localStorage.setItem('counter', count);
if (count <= 0) {
clearInterval(counter);
return;
}
}
setTimeout(() => $(this).attr('src', initNextImagePath), timer);
localStorage.setItem('imagepath', initImagePath);
localStorage.setItem('nextimagepath', initNextImagePath);
}
function loadDefaultValues() {
const initImagePath = localStorage.getItem('imagepath');
const initNextImagePath = localStorage.getItem('nextimagepath');
const counter = localStorage.getItem('counter');
aktivereSkift(initImagePath, initNextImagePath, counter);
}
loadDefaultValues();
$(".toilet").on("click", () => {
aktivereSkift('/lib/pictures/toiletBegyndt.png', '/lib/pictures/toiletSlut.png');
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="toilet" src="~/lib/pictures/toilet.png" style="height:150px;width:150px;" />
发布于 2021-03-16 00:15:22
好的,这是一个有效的代码片段,我希望它能做你想要的事情。LocalStorage在代码片段中不起作用(出于安全考虑),只需取消注释所有的localStorage内容:
function aktivereSkift(
initImagePath = null,
initNextImagePath = null,
count = 5
) {
console.log("clicked =", this);
if (initImagePath === null || initNextImagePath === null) {
return false;
}
$(this).attr("src", initImagePath);
let timer = count * 1000;
let counter = setInterval(timerLS.bind(this, count), 1000);
function timerLS() {
count = count - 1;
// localStorage.setItem("counter", count); --> Doesn't work in a Stackoverflow snippet
if (count <= 0) {
clearInterval(counter);
return;
}
}
setTimeout(() => $(this).attr("src", initNextImagePath), timer);
// localStorage.setItem("imagepath", initImagePath);
// localStorage.setItem("nextimagepath", initNextImagePath);
}
function loadDefaultValues() {
const initImagePath = localStorage.getItem("imagepath");
const initNextImagePath = localStorage.getItem("nextimagepath");
const counter = localStorage.getItem("counter");
aktivereSkift(initImagePath, initNextImagePath, counter);
}
// loadDefaultValues(); --> LocalStorage doesn't work inside a Stackoverflow snippet
$(".toilet").on("click", function () {
aktivereSkift.call(
this,
"https://picsum.photos/200",
"https://picsum.photos/200?grayscale"
);
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="toilet" src="https://picsum.photos/200" style="height:150px;width:150px;" />
发布于 2021-03-15 18:36:52
this关键字引用声明this关键字的内部函数。在这种情况下,this引用的是函数,而不是img元素。
$("#img").attr("src", theImagePath);https://stackoverflow.com/questions/66636255
复制相似问题