动态创建的文本字段的不同行为

Different behavior of dynamically created text fields

本文关键字:字段 创建 文本 动态      更新时间:2023-09-26

我有一组文本字段,当我单击时,文本会消失并在模糊时返回(经典表单行为),还有一个按钮,当您单击时,您有一个jQuery模式窗口。但是,我想允许用户使用 jQuery 添加更多文本字段(和按钮)。问题是,我的用户添加的字段的行为方式与静态字段不同。例如,当我单击按钮(用户添加的按钮)时,模态不会出现。这是我的代码,给你一个更好的主意:

<form method="post" action="payment.php">
    <div id="formulaire">
        <div class="formelements">
            <input type="text" name="from" value="Ex: English(UK)" style="width:100px;margin-right:0px;"
            class="langfield">
            <div class="droparrow" id="arrow"></div>
            <input type="text" name="from" value="Ex: French(FR)" style="width:100px;margin-right:0px;"
            class="langfield">
            <div class="droparrow"></div>
            <input type="text" name="nopages" id="nopages" value="Ex:4">
            <div class="uploadbtn"></div>
        </div>
    </div>
</form>

这是我的JavaScript代码来更改字段的行为:

$('.formelements input').each(function () {
    var default_value = this.value;
    $(this).focus(function () {
        if (this.value == default_value) {
            this.value = '';
            $(this).css("font-weight", "bold");
            $(this).css("color", "#323232");
        }
    });
    $(this).blur(function () {
        if (this.value == '') {
            this.value = default_value;
            $(this).css("font-weight", "normal");
            $(this).css("color", "#9e9e9e");
        }
    });
});
/* Modals script start UPDATED AS REQUESTED  */
   $('#formelements').on("click", ".uploadbtn", function () {
    $("#modaldialog").dialog({
    height: 332,
    width: 625,
    modal: true
    });
   });

提前感谢您的帮助!

要修复"无模式对话框"问题,请替换

$(".uploadbtn").click(function () {
    $("#modaldialog").dialog({
        height: 332,
        width: 625,
        modal: true
    });
});

$('.formelements').on("click", ".uploadbtn", function () {
    $("#modaldialog").dialog({
        height: 332,
        width: 625,
        modal: true
    });
});

这使用 .on() 函数,该函数适用于新创建的 DOM 元素。您可以将#formelements替换为加载时存在的任何父元素 - 表单可以在此处使用

注意

on()方法至少需要 jQuery 1.7 才能工作......如果你有一个以前的版本,你可以使用委托():

$('.formelements').delegate(".uploadbtn", "click", function () {
    $("#modaldialog").dialog({
        height: 332,
        width: 625,
        modal: true
    });
});