我在标题中提到的可能吗?
我想用它来检查元素的存在,如下所示:
if($('#item')){...}
有什么想法吗?
这是我使用它的代码:
if($('#auto_redirect_in_3_s').length)//I "wished" $('#auto_redirect_in_3_s')
{
var timer = setTimeout("document.location.href = index_url;",3000);
}
描述: 如果我输入php代码,则意味着页面必须在3秒内重定向。
答案 0 :(得分:2)
没有。 jQuery
工厂函数(别名为$
)返回jQuery集合对象的实例 - 即使选择与任何内容都不匹配。如果选择器不匹配,则集合为空,但它仍然是一个对象,因此它的计算结果为true。您必须检查.length
以查看是否有任何内容。
然而,.length
的这种检查通常是不必要的,因为jQuery如何工作,并且往往是逻辑不佳或对jQuery的误解的标志。因此,如果您发布代码,我们可能会帮助清理它。
<强>更新强>
好的,您更新的问题提供了以下代码:
if( $( '#auto_redirect_in_3_s' ).length ) //I "wished" $('#auto_redirect_in_3_s')
{
var timer = setTimeout( 'document.location.href = index_url;' ,3000 );
}
你正在做的事情并不可怕,可以被认为是.length
的好用法。但是,请允许我向您展示一些其他方法来完成同样的事情。 我不是说你应该执行以下任何操作,只是显示有多种方法可以对猫进行换肤,并希望在一些示例中向您展示更多jQuery用法。强>
如果您从客户端而不是使用HTTP标头重定向页面,最好的方法是使用meta
标记:
<meta http-equiv="refresh" content="3; url=http://example.com/">
如果你希望将它保存在JS中,你可以避免根据元素的存在来做,而是根据某些输入所持有的值:
<input type="hidden" id="auto_redirect_do" value="1" />
<input type="hidden" id="auto_redirect_url" value="http://example.com/" />
<input type="hidden" id="auto_redirect_delay" value="3000" />
<script type="text/javascript>
$( function()
{
if( $( '#auto_redirect_do' ).val() === '1' )
{
window.setTimeout(
function()
{
window.location = $( '#auto_redirect_url' ).val();
},
$( '#auto_redirect_delay' ).val()
);
}
} );
</script>
或者,在输入中使用JSON编码值(或元素上的数据attr):
<input type="hidden" id="auto_redirect" value="{"do":true,"url":"http:\/\/www.example.com","delay":3000}" />
<script type="text/javascript>
$( function()
{
var auto_direct = JSON.parse( $( '#auto_redirect' ).val() );
if( auto_direct.do === true )
{
window.setTimeout(
function()
{
window.location = auto_redirect.url;
},
auto_redirect.delay
);
}
} );
</script>
回到你寻找元素存在的版本,如果你想避免使用.length
并使用jQuery的链接,你可以执行以下操作:
$( '#auto_redirect_in_3_s' ).each( function()
{
/*
We got in here because the element was present
*/
window.setTimeout( function()
{
window.location = index_url;
}, 3000 );
/*
Return false from this function in case we matched more
than one--no need to setup the redirection multiple times
*/
return false;
} );