开发者

Can this jQuery code snippet be shortened?

开发者 https://www.devze.com 2022-12-24 18:32 出处:网络
I have just started using jQuery and although following code gets the job done, I have a feeling that it can 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.

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.

Update:

This 开发者_StackOverflow社区is simplified HTML that I'm modifying. The place where I add content is marked with ##1## and ##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

$('#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 has a large variety of selectors that can probably replace the indexed sibling. If you show us your HTML, we can find you one.

Other notes:

You can set multiple attributes in one call:

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

精彩评论

暂无评论...
验证码 换一张
取 消