gpt4 book ai didi

javascript - 放置在 .js 单独文件中时 jQuery 函数不起作用

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

我有一个带有此 jQuery 函数的 php 文件正常工作(基本上它识别每个 '.limitCharacters' 元素,计算其宽度和高度并在其上制作一些内容):

$('.tableContent').find('.limitCharacters').each(function(){

var percent = ((($(this).width()) / ( $(this).closest('div').width()))*100);
if (percent > 95 || $(this).height() > 40){
$(this).css('white-space','nowrap').css('color','red');
$(this).parent().css('width', '85%').css('display','inline-block').css('overflow','hidden');
$(this).parents().eq(1).css('height','36px');
}
})

但是当我尝试将它移动到我单独的 .js 文件(其中已经有许多函数从这个 php 文件调用,并且工作正常)时,为了在我需要时从我的 php 文件调用它,它不起作用。这就是我在单独的 .js 文件中创建它的方式:

function limitCharactersWidth(actualWidth, actualHeight, maxSpace, newSpace){
if (actualWidth > maxSpace || actualHeight > 40){
$(this).css('white-space','nowrap').css('color', 'red');
$(this).parent().css('width', newSpace).css('display','inline-block').css('overflow','hidden');
$(this).parents().eq(1).css('height','36px');}}

这是我从 php 文件中调用它的方式:

$('.tableContent').find('.limitCharacters').each(function(){

var actualWidth = ((($(this).width()) / ( $(this).closest('div').width()))*100);
var height = $(this).height();
limitCharactersWidth(actualWidth,height,'90','80');
})

从理论上讲,它是相同的,只是在第二种情况下,我将变量传递到我的 .js 单独文件,它应该做出相同的 react 。我错过了什么?

最佳答案

你的问题是$(this),在你的原始代码中$(this)指的是元素.limitCharacters,正如你所言将函数分隔为单独的 JS 文件,您必须将 $(this) 的引用传递给您的函数

试试这个,这里我添加了新参数obj

function limitCharactersWidth(obj, actualWidth, actualHeight, maxSpace, newSpace){
if (actualWidth > maxSpace || actualHeight > 40){
$(obj).css('white-space','nowrap').css('color', 'red');
$(obj).parent().css('width', newSpace).css('display','inline-block').css('overflow','hidden');
$(obj).parents().eq(1).css('height','36px');}}

使用

$('.tableContent').find('.limitCharacters').each(function(){
var actualWidth = ((($(this).width()) / ( $(this).closest('div').width()))*100);
var height = $(this).height();
limitCharactersWidth(this, actualWidth,height,'90','80'); //Passed this
})

关于javascript - 放置在 .js 单独文件中时 jQuery 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23195135/

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