gpt4 book ai didi

javascript - 如何创建一个函数并向其传递一个变量?

转载 作者:行者123 更新时间:2023-11-28 13:35:47 24 4
gpt4 key购买 nike

我对 js 相当陌生,但对 jQuery 不太了解,所以我不知道到底要搜索什么才能回答我的问题,希望这里有人可以帮助我。

简而言之 - 我有一个非常简单的 jQuery 来检查下一个和上一个元素。我想通过将函数分开来使其变得更整洁。

这是我当前的代码:

$(function() {

$('.filmstrip img').on('click', function(){
var new_src = $(this).attr('data-src');
$('.mainView img.current').attr('src', new_src);

//get the previous element's data source
var prevImg = $(this).closest("li + *").prev().find('img').attr('data-src');
if(prevImg === undefined){
console.log('there isnt a prev img');
}
if(prevImg != undefined){
console.log('the previous image is: '+prevImg);
}

//get the next element's data source
var nextImg = $(this).closest("li + *").next().find('img').attr('data-src');
if(nextImg === undefined & prevImg != undefined){
console.log('You are at the last image');
}
if(nextImg != undefined){
console.log('the next image is: '+nextImg);
}

});

});

这就是我的目标(注意:这不会按预期工作):

$(function() {

$('.filmstrip img').on('click', function(){
var new_src = $(this).attr('data-src');
$('.mainView img.current').attr('src', new_src);
getThePrevAndNextImages();
});

function getThePrevAndNextImages(){
//get the previous element's data source
var prevImg = $(this).closest("li + *").prev().find('img').attr('data-src');
if(prevImg === undefined){
console.log('there isnt a prev img');
}
if(prevImg != undefined){
console.log('the previous image is: '+prevImg);
}

//get the next element's data source
var nextImg = $(this).closest("li + *").next().find('img').attr('data-src');
if(nextImg === undefined & prevImg != undefined){
console.log('You are at the last image');
}
if(nextImg != undefined){
console.log('the next image is: '+nextImg);
}
}

});

我认为这不起作用的原因是因为它没有传递事件元素?

我得到的console.log是:“没有上一个img”。

最佳答案

在之前的实现中,每个语句都位于事件处理程序下。您使用 this 表示被单击的元素。但在函数的上下文中。这是不存在的。 所以解决办法就是传入被点击的元素

使用

$(function () {
$('.filmstrip img').on('click', function () {
var new_src = $(this).attr('data-src');
$('.mainView img.current').attr('src', new_src);
getThePrevAndNextImages(this);
});

function getThePrevAndNextImages(obj) {
//get the previous element's data source
var prevImg = $(obj).closest("li + *").prev().find('img').attr('data-src');
if (prevImg === undefined) {
console.log('there isnt a prev img');
}
if (prevImg != undefined) {
console.log('the previous image is: ' + prevImg);
}
//get the next element's data source
var nextImg = $(obj).closest("li + *").next().find('img').attr('data-src');
if (nextImg === undefined & prevImg != undefined) {
console.log('You are at the last image');
}
if (nextImg != undefined) {
console.log('the next image is: ' + nextImg);
}
}
});

关于javascript - 如何创建一个函数并向其传递一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21436441/

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