开发者

How do I access specific elements within a div tag using $(this)?

I've got some javascript that allows me to load states into a dropdown using json anytime the user changes the country. This works great except that I can't have more than one of combination of country/state dropdowns on a page. So, given HTML like the following:

<div id="div1" data-ajax-address="owner">
   <select id="country1" data-ajax-address="country"></select>
   <select id="state1" data-ajax-address="state"></select>
</div>
<div id="div2" data-ajax-address="owner">
    <p>
        <select id="country2" data-ajax-address="country"></select>
    </p>
    <p>
        <select id="state2" data-ajax-address="state"></select>
    </p>
</div>

I want to be able to do something like this:

$('div[data-ajax-address="owner"]').each(function() {
    $(this).children('select[data-ajax-address="country"]).change(function() {
        ....
    });
});

to access the country/state select elements within the div. I can't use children() because they could be embedded within another element -- like the country2 & state2 being embedded inside of t开发者_如何转开发he paragraph tags.

Any ideas on how I can accomplish this?

Thanks.


Try something like:

$('div[data-ajax-address="owner"]').each(function() {
    $(this).find('select[data-ajax-address="country"]').change(function() {
        ....
    });
});

More info: http://api.jquery.com/find/


You can do a direct selection of the descendants if you want to:

    $('div[data-ajax-address="owner"] select[data-ajax-address="country"]').change(function() {...});

Shorter and same precision

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜