【问题标题】:Unable to change style in jquery mobile无法在 jquery mobile 中更改样式
【发布时间】:2013-11-14 09:54:32
【问题描述】:

在 jQuery mobile 中使用 $(this).addClass('errorClassText') 时无法更改样式。 我真的需要使用 $(this) 因为我有几个表单字段,我想在其中应用验证。有人可以建议我哪里出错了。

jQuery 脚本:

<script>
    $(document).on('pageinit', function(){
        $(".form2 input").click(function() {    
            $(this).keyup(function()
                {
                    $(this).addClass('errorClassText')
                });
        }); 
    });

</script>

带有 css 样式的 HTML 代码:

<!DOCTYPE html>

<html>
<head>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>

<style>
        .errorClassText{
            color: #ff6666;
        }
</style>
</head>

<body> 
<form class='form2' name= "form" action="">       
    <input type="text" name="buildingname" id="house_name" >
    <label id="house_name_error" for= "house_name"></label>
    <input type="text" name="doorno" id="doorno" >
    <label class= "" id="doorno_error" for= "doorno"></label>
    <button type="submit" class="button" id="submit_btn" name="submit" >Submit</button>
</form>

</body>
</html>

【问题讨论】:

  • 我会假设添加一个类是可行的,但与包含的样式表相比,CSS 规则不够具体。

标签: javascript jquery html css jquery-mobile


【解决方案1】:

当用户在键盘上释放一个键时,keyup 事件被发送到一个元素。但是,在您的实例中,您试图在点击事件中触发(点击 .form2 输入)。因此,我想您的代码当前正在寻找在用户单击该字段时释放键盘上的键。不会发生。

如果您在 click 函数内部和 keyup 函数外部添加一个控制台日志,并且在 keyup 函数内部添加一个不同的控制台日志,您应该能够看到触发的内容和时间(我不会根本不认为 keyup 功能正在被触发)。

在您的 sn-ps 代码中似乎没有任何内容可以将任何内联样式添加到输入中(这是看不到应用错误样式的另一个原因,因为这些样式会覆盖分配给新样式的样式类)。

试试这个:

    $(document).on('pageinit ready', function(){
            $(".form2 input").keyup(function(){
                    $(this).addClass('errorClassText')
            });
    });

【讨论】:

    【解决方案2】:

    使用key up event 而不使用click 之类的,

    $(document).on('pageinit ready', function(){
        $(".form2 input").keyup(function(){
             $(this).addClass('errorClassText')
        });
    });
    

    已更新,如果你想addClass 换成particular input element,比如doorno,那么试试吧,

     $('#doorno').on('keyup',function(){
        $(this).addClass('errorClassText')
     });
    

    【讨论】:

    • 通过使用上面的代码,如果任何输入元素中有keyup事件,则函数正在执行。这是不希望的。
    • 是的,您可以通过更改 jquery selector (如 $('#doorno').on('keyup',)来实现
    • 我同意使用上面的而不是 $(this) 会起作用,这意味着我需要为每个字段重复(我在一个表单中有 9 个字段)。
    • 使用可以使用 :not selector see api.jquery.com/not-selector like $('form:input[type="text"]:not("#doorno")) 选择除#doorno之外的所有input elements
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多