开发者

jQuery: .closest adds the class attribute, but not my intended value

开发者 https://www.devze.com 2023-02-16 18:50 出处:网络
Quick preview of the problem: using .closest(), I\'m able to stick a class attribute on all inst开发者_JAVA技巧ances of the target element, but it won\'t insert the class value on any that have an ext

Quick preview of the problem: using .closest(), I'm able to stick a class attribute on all inst开发者_JAVA技巧ances of the target element, but it won't insert the class value on any that have an extra <div> in the ancestor DOM.

First, here's the jQuery:

// Throw class="errorWrap" on any <li> element that contains a field that doesn't validate
highlight: function(element) {
    $(element).closest("li").addClass("errorWrap");
}

(…The 'highlight:' is part of the Validate plug-in…)

And here's a snippet of my HTML:

<li>
    <div>
        <span class="reqField">*</span> Have you been employed with us before?<br />
        <label class="radioInput"><input type="radio" name="app_prior_employ" value="Yes" /> Yes</label>
        <label class="radioInput"><input type="radio" name="app_prior_employ" value="No" /> No</label>
    </div>

    <div>
        <label for="app_prior_employ_date">If <em>yes</em>, when were you employed?</label><br />
        <input type="text" name="app_prior_employ_date" value="" size="40" id="app_prior_employ_date" />
    </div>
</li>

…now, with the above, the class attribute will be added to the opening <li> tag when it's supposed to, but it's value will be empty rather than errorWrap

As I mentioned at the top of this question, this issue occurs on only instances that have the <div> elements in the mix (as they do immediately above). This issue does not occur on other instances where the <div> is not in place, such as:

<li>
    <span class="reqField">*</span> Can you travel if a job requires it?<br />
    <label class="radioInput"><input type="radio" name="app_travel_for_job" value="Yes" /> Yes</label>
    <label class="radioInput"><input type="radio" name="app_travel_for_job" value="No" /> No</label>
</li>

I can't figure out why jQuery would succeed in adding the class attribute everywhere I want it to, but fail to insert the value I've defined only in those that have an extra element in the DOM. Am I using .closest() improperly?

Added moments later: Here's a marked-up screen shot of the issue: http://i.stack.imgur.com/aiiaX.png


You're using closest() properly, but maybe the context in which the highlight() function is wrong in that instance. In the scripts inspector, put a breakpoint inside the highlight function, and see if element is actually the input you think it is.

Alternatively, you say the li has a class, but no value when the div is in the mix. Maybe the class is getting set then immediately unset. Using the script inspector and setting breakpoints will help you figure that out.


Use parents instead

$(element).parents("li").addClass("errorWrap");
0

精彩评论

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