简体   繁体   English

javascript 中的条件基于当前显示的页面

[英]conditionals in javascript based on page currently showing

because of some problems with joomla "in-content javascript" I have to give all my js logic to one file, but there are problems with inconsistence of dom elements across my site (it is ajax driven, so there is only one script and various DOMs).由于 joomla “in-content javascript” 的一些问题,我必须将我所有的 js 逻辑都提供给一个文件,但是我的站点中的 dom 元素不一致存在问题(它是 ajax 驱动的,所以只有一个脚本和各种DOM)。 What is the best solution to make some conditionals solving this problem..使某些条件解决此问题的最佳解决方案是什么。

Is it checking $(selector).length , or is there any better solution..是检查$(selector).length ,还是有更好的解决方案..

And in case of the $(selector).length , is there a way to save this selector to variable (performance issues) for example some kind of如果是$(selector).length ,有没有办法将此选择器保存到变量(性能问题),例如某种

 var selector = ($(selector).length !== 0) ? this : false ;
 if(selector) { makeSomething; }

The this is actually pointing to Window object..So is there any way to make it like this without need of reselection?这实际上指向 Window object ..那么有什么方法可以使它像这样而不需要重新选择?

Thanks谢谢

var $obj = $('selector');
if ($obj.length) { makeSomething(); }

Actually, this is only meaningful if you are searching for the existence of a certain element (that might identify a whole page) and running several operations based on that.实际上,这仅在您搜索某个元素的存在(可能标识整个页面)并基于该元素运行多个操作时才有意义。

If you just want to do something on the elements like如果您只想对元素做一些事情,例如

 $('selector').append('x');

the condition might be useless, because if the jQuery collection is empty, the methods won't run anyways (as pointed out by @Gary Green ).该条件可能没用,因为如果 jQuery 集合为空,则方法无论如何都不会运行(正如@Gary Green所指出的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM