是否可以使用单个jQuery链定义多个变量?
var sectionTable = jQuery("#sectionsTable");
var sectionTableRows = sectionTable.find("tr");
var sectionTableColumns = sectionTableRows.find("td");
Run Code Online (Sandbox Code Playgroud)
如果有可能,我不知道语法是什么,但如果你把3个变量放在上面,你怎么能把它们链接起来呢?它会被认为是好的做法吗?
非常感谢
克里斯
编辑:哇,谢谢你的所有评论.对于模糊不清,我所追求的是从父变量定义子变量的更好方法(如果存在).这就是为什么我想到使用链条并想知道是否存在一种方式.感谢您的宝贵意见.
我可能并不真正理解你想要什么或需要什么,但你可以为jQuery包装集链接任何函数并"结束"它,因此"返回"到前一集.例如:
jQuery("#sectionsTable").css('background-color', 'red')
.find('tr').css('background-color', 'yellow')
.find('td').css('background-color', 'black')
.end() // back to 'tr'
.doSomething()
.end() // back to '#sectionsTable'
.doSomething();
Run Code Online (Sandbox Code Playgroud)
但是,这意味着您只需要访问这些元素一次.如果以后需要在代码中访问它们,则应始终将结果引用存储在变量中,这有几个性能原因.
如果你真的想要,一切皆有可能:
在我的头脑中,你可以尝试做这样的事情:
var sectionTable,
sectionTableRows,
sectionTableColumns = $('td', (sectionTableRows = $('tr',(sectionTable = $('#sectionsTable')))));
Run Code Online (Sandbox Code Playgroud)
另一个想法是构建一个迷你插件,将当前的jquery对象分配给对象的某个字段:
jQuery.fn.assignTo = function(variableName,namespace){
var ns = namespace || window;
ns[variableName] = this;
return this;
}
Run Code Online (Sandbox Code Playgroud)
通过这种代码安静,您可以执行以下操作:
var sections = {};
jQuery("#sectionsTable")
.assignTo('sectionTable',sections)
.find("tr")
.assignTo('sectionTableRows',sections)
.find("td")
.assignTo('sectionTableColumns',sections);
console.log(sections.sectionTable);
console.log(sections.sectionTableRows);
console.log(sections.sectionTableColumns);
Run Code Online (Sandbox Code Playgroud)
当然,如果你没有指定任何命名空间,那么变量将是全局的(将附加到window对象);
无论如何,我不鼓励你使用这些例子,因为使代码的可读性恶化而不使用更少的等号和var声明也没有多大意义.
| 归档时间: |
|
| 查看次数: |
13122 次 |
| 最近记录: |