[英]jQuery function not working when placed on .js separate file
我有一個與此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單獨的文件,並且它應該做出相同的反應。 我想念什么?
您的問題是$(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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.