开发者

jQuery code works for console but not in-page

开发者 https://www.devze.com 2022-12-25 03:36 出处:网络
I have a form element defined as: <div class=\"field\"> <div class=\"name\"> <label for=\"User_LastName\">

I have a form element defined as:

<div class="field">
    <div class="name">
        <label for="User_LastName">
            Last name: <span class="asterisk">*</span></label>
    </div>
    <div class="value">
        <%= Html.TextBox("User.LastName", Model.LastName)%>
        <%= Html.ValidationMessage("User.LastName")%>
    </div>
</div>

and a jQuery selector that is supposed to detect when the input gets focus and highlight the parent:

    $("input").focus(function() {
    //watching for an event where an input form comes into focus
        $(this).parent().addClass("curFocus").children("div").toggle();
    });

If i paste this code into firebug's console - things work开发者_如何学Python as planned. However, i'm running this from a 'RenderPartial' .net mvc page. Other jQuery code sitting within the same $(document).ready(function() { block work correctly.

The form uses html helpers to generate the inputs which might complicate the process somewhat - but even so... i'm seeing correct behavior when that code's in console but not in a 'real-time' page.

How do i troubleshoot this?


When you're rendering a partial, the $("input") selector doesn't find the element to rig this up to, because it isn't there yet. If you change it to a live event, it'll work on elements added after document.ready executes.

To fix it, use .live() like this:

$("input").live('focus', function() {
  $(this).parent().addClass("curFocus").children("div").toggle();
});

Note: requires jQuery 1.4.1+


Use setTimeOut

  setOut(function(){
        $("input").focus(function() {
             //watching for an event where an input form comes into focus
             $(this).parent().addClass("curFocus").children("div").toggle();
        });
  },500) 
0

精彩评论

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