gpt4 book ai didi

javascript - 如何在代码的其他部分调用此函数?

转载 作者:行者123 更新时间:2023-11-29 23:46:51 26 4
gpt4 key购买 nike

如果这是一个非常愚蠢的问题,请原谅我。我是 JS 的新手,我想知道如何在我的代码的其他部分使用这个函数。我查看了教程和其他网站,但他们定义函数的方式似乎与我在这里看到的不同。任何人都可以向正确的方向轻推我吗?

$('.message_div').each(function message_function()
{
console.log("One liner");
var th = $(this);
var ih = $(this).outerHeight(); // outer height
var oh = $(this).find('.message').outerHeight();
console.log("Oh", oh);
var txt = $(this).find('.message').html();
console.log("Ih", ih);



if (oh > ih)
{
th.html('');
th.html('<marquee class="message" direction="up" scrollamount="1" scrolldelay="0">' + txt + '</marquee>')
}
});

//message_function(); -----> Is this the right way?

最佳答案

关于 jQuery 的功能,这里有几个错综复杂的地方。稍后引用此函数的简单方法是将其存储在变量中:

function message_function()
{
console.log("One liner");
var th = $(this);
//... (rest of function omitted for brevity)
}

$('.message_div').each(message_function);//note that the function handle is used here,
//and not the result of the function which would
//have used the () to call it

///and then later on
message_function();

但是,这里的问题在于this。 jQuery 将在后台绑定(bind) this(这意味着它在 each 中工作正常),但是为了正确地分别调用消息函数,您需要准备好一个元素绑定(bind)。例如,

var element = document.querySelector("div");
message_function.call(element);

或者:

var element = document.querySelector("div");
var elementMessage = message_function.bind(element);
elementMessage();

下面是关于什么是 this 以及 jQuery 如何与它交互的更广泛的解释:https://stackoverflow.com/a/28443915/1026459

关于javascript - 如何在代码的其他部分调用此函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668359/

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