我有一个php文件,这个jQuery函数正常工作(基本上它识别每个'.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单独文件,它应该反应相同。我错过了什么?
答案 0 :(得分:3)
您的问题是$(this)
,在原始代码中$(this)
引用了元素.limitCharacters
,因为您已将函数分离为单独的JS文件,您必须传递{{{ 1}}到你的功能
试试这个,我在这里添加了新参数$(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');}}