如标题所示,我想在某些条件下填充变量
我以为我可以这样做,但没有:
var content = $(function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
});
所以我认为javascript变量'content'将是代表dom中元素的jquery对象之一。但似乎“内容”就是功能。
我猜你想象我想要做什么.. JQuery 的语法是什么?
谢谢
最佳答案
$(function() { })
是 DOMReady 事件的短代码。您需要显式定义一个函数,然后将返回值分配给您的变量。
例如:
function getObj()
{
if($('#content').length)
{
return $('#content');
}
if($('#content_no_decoration').length)
{
return $('#contenu_no_decoration');
}
if($('#full_content').length)
{
return $('#full_content');
}
if($('#full_content_no_decoration').length)
{
return $('#full_content_no_decoration');
}
}
然后您可以将该值指定为:
var content = getObj();
当 DOM 准备好时,您需要调用赋值,否则选择器将不会按预期触发。例如:
$(function() {
var content = getObj();
});
关于javascript - 使用 jquery 在条件下定义 JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20706630/