jQuery只对第一个CodeIgniter视图有效,而对第二个视图无效



我的应用程序中有两个CodeIgniter视图,它们都有一个文本字段。我的问题是,当我的应用程序加载时,我的jQuery代码只在第一个CodeIgniter视图上工作。当我的应用程序显示第二个视图时,我的jQuery代码不起作用。

$(document).ready(function() {
    $(".input-field").attr("value","I'm looking for...");
    var text = "I'm looking for...";
    $(".input-field").focus(function() {
        $(this).addClass("active");
        if($(this).attr("value") == text) $(this).attr("value", "");
    });
    $(".input-field").blur(function() {
        $(this).removeClass("active");
        if($(this).attr("value") == "") $(this).attr("value", text);
    });
});

以下是我的脚本标记,位于两个CodeIgniter视图的头部。此外,两个视图都具有相同的类名input-field。为什么我的jQuery不能在第二个视图上工作?

<script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="scripts/script.js"></script>

您需要使用事件委派,因为您似乎在处理动态元素

事件被更改为聚焦和聚焦,因为根据定义,聚焦和模糊不会使起泡

$(document).ready(function () {
    $(".input-field").attr("value", "I'm looking for...");
    var text = "I'm looking for...";
    $(document).on('focusin', ".input-field", function () {
        $(this).addClass("active");
        if ($(this).attr("value") == text) $(this).attr("value", "");
    });
    $(document).on('focusout', ".input-field", function () {
        $(this).removeClass("active");
        if ($(this).attr("value") == "") $(this).attr("value", text);
    });
});

相关内容

最新更新