【问题标题】:How to set value to multiple elements by name attribute at once (ExtJs 4)如何一次通过名称属性为多个元素设置值(ExtJs 4)
【发布时间】:2016-02-04 15:02:23
【问题描述】:

在 JQuery 中,我可以通过这种方式一次为多个元素设置值:

<form action="" id="mainForm">
    <input type="text" name="Phone" class="deftext" value="" > 
    <input type="text" name="Number" class="deftext" value="" >
    <input type="text" name="Name" class="deftext" value="" > 
    <input type="text" name="Lastname" class="deftext" value="" >
    <input type="text" name="Middlename" class="deftext" value="" > 
    <input type="text" name="Age" class="deftext" value="" >
    <input type="text" name="Email" class="deftext" value="" > 
    <input type="text" name="Occupation" class="deftext" value="" >
</form>

$('#mainForm .deftext').val("hello");
// OR
$('#mainForm input:text').val("");

ExtJS 4中是否有类似的方法将以下代码修改为单行?

Ext.getCmp('mainForm').down('[name=Phone]').setValue('');
Ext.getCmp('mainForm').down('[name=Number]').setValue('');
Ext.getCmp('mainForm').down('[name=Name]').setValue('');
....

【问题讨论】:

    标签: extjs extjs4.1


    【解决方案1】:

    您的 JQuery 代码不是真正可读的,因为在查看函数时,您看不到有多个字段受到影响。这就是 ExtJS 不支持这种语法的原因。要么你使用

    Ext.getCmp('mainForm').down('[name=Phone]').setValue('');
    Ext.getCmp('mainForm').down('[name=Number]').setValue('');
    

    或者你使用

    Ext.getCmp('mainForm').getForm().setValues({
        Phone: '',
        Number: ''
    });
    

    与您的 JQuery 示例不同,这两个都是可读的,因为我不必知道哪些类已应用于哪些字段。

    如果要将所有字段重置为上次form.loadRecord 操作期间设置的值,或者如果没有执行form.loadRecord 操作,则使用初始值,请使用form.reset

    Ext.getCmp('mainForm').getForm().reset();
    

    【讨论】:

    • jQuery 代码对我来说似乎很可读。知道多个属性受到影响(它们不是字段)与代码是否可读是分开的。
    【解决方案2】:

    好吧,如果子组件有共同点(例如 xtype),您可以执行类似的操作

    Ext.getCmp('mainForm').query('textfield').each(function(component){component.setValue('')});
    

    但是不行,你不能在组件数组上使用组件方法。

    【讨论】:

    • 好吧,乍一看不,Ext.Array.each() 方法只使用 for 循环(源 - docs.sencha.com/extjs/4.2.1/source/…),你必须为数组中的每个组件调用 setValue() 方法所以我猜你无论如何都必须遍历数组。据我所知,for 循环通常是在 JS 中循环遍历数组的最快方法,所以我猜它并不“昂贵”(我敢打赌,当你调用 $('.deftext').val("hello"); 时,JQuery 会做类似的事情)。
    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2011-11-30
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多