简体   繁体   English

这个jQuery代码片段可以缩短吗?

[英]Can this jQuery code snippet be shortened?

I have just started using jQuery and although following code gets the job done, I have a feeling that it can be shortened. 我刚开始使用jQuery,虽然下面的代码完成了工作,但我觉得它可以缩短。

var accountAddress = $(document.createElement("input")).addClass("readOnly")
        .attr("contentEditable", "false").attr("id", "d_accountAddress");

$("#customerid_c").next().next().next().append(accountAddress);

If it is not clear - what I'm doing is creating new input tag, assigning class and making it read-only, then positioning new input two TD's to the right of some known text. 如果不清楚 - 我正在做的是创建新的输入标签,分配类并使其成为只读,然后将新输入定位两个TD位于某些已知文本的右侧。

Update: 更新:

This is simplified HTML that I'm modifying. 这是我正在修改的简化HTML。 The place where I add content is marked with ##1## and ##2## . 我添加内容的地方标有## 1 #### 2 ##

<TD id=customerid_c>
    <LABEL for=customerid>Customer</LABEL>
</TD>
<TD id=customerid_d></TD>
<TD class=ms-crm-Field-Normal>
    <LABEL>##1##</LABEL>
</TD>
<TD>##2##</TD>

Yes, it can. 是的,它可以。

$('#customerid_c').nextAll().eq(2)
    .append('<input class="readOnly" id="d_accountAddress" />');

In jQuery 1.4.2, you can write 在jQuery 1.4.2中,您可以编写

$('#customerid_c~:eq(2)')
    .append('<input class="readOnly" id="d_accountAddress" />');

This selector, which does not work correctly in earlier versions of jQuery, uses the Next Siblings Selector ( ~ ) to select all sibling elements following #customerid_c , then uses the :eq selector to select the third (zero-based) element matched by the other selector. 此选择器在早期版本的jQuery中无法正常工作,使用Next Siblings Selector( ~选择#customerid_c之后的所有兄弟元素,然后使用:eq选择器选择与之匹配的第三个(从零开始)元素其他选择器。

jQuery has a large variety of selectors that can probably replace the indexed sibling. jQuery有很多种选择器可以替代索引的兄弟。 If you show us your HTML, we can find you one. 如果您向我们展示您的HTML,我们可以找到您的HTML。

Other notes: 其他说明:

You can set multiple attributes in one call: 您可以在一个调用中设置多个属性:

$(something).attr({ id: 'd_accountAddress', type: 'text' });

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

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