【问题标题】:jquery dialog box remembers previous inputjquery对话框记住以前的输入
【发布时间】:2026-01-07 07:15:02
【问题描述】:

请帮助我。 我有一个包含多个文本输入的表单,这些输入具有不同的 id 但与下面的类相同

<input id="user_1" type="text" class="user-list" />
<input id="user_2" type="text" class="user-list" />
<input id="user_3" type="text" class="user-list" />

现在使用类定义,我正在调用 jquery 对话框,如下所示

$('.user-list').click(function(){
    $( "#user-form" ).dialog( "open" );
    tableOpen(this);    
});

这里的用户表单是下面的名称列表

<div id="user-form" title="Select Employee" >
<table id="user-table">
<thead><th>Employee No</th><th>Name</th></thead>
<tbody>
<tr><td>Employee-1 No</td><td>Employee-1 Name</td></tr>
<tr><td>Employee-1 No</td><td>Employee-1 Name</td></tr>
<tr><td>Employee-1 No</td><td>Employee-1 Name</td></tr>
</tbody>
</table>
</div>

现在我使用对话框在对话框中打开 div 元素

$( "#user-form" ).dialog({
create: function() {       },  
autoOpen: false,
cache: false,
closeOnEscape: true,
height: 400,
width: 600,
modal: true,
buttons: {
    Cancel: function() { $( this ).dialog( "close" );}
},
close: function() {}
});

对话框按预期出现。现在我在 tableOpen 函数的用户表行中添加一个点击事件,用于选择用户。

function tableOpen(selInput)
{
    alert($(selInput).id().text()+"first");
    $('#user-table tr').click( function() {
           alert($(selInput).id().text()+"second");
    });
    //some other function here from displaying the selected user to input field
}

问题从这里开始。我第一次通过单击选择用户时,tableOpen 函数中的两个警报都只执行一次。但是在随后单击时,第一个警报仅显示一次,但第二个警报还会记住以前的单击,并且我之前单击的所有时间都会显示警报。

【问题讨论】:

  • 您的 javascript 与 html 是否在同一个文件中?我有这个完全相同的问题。在我将所有 javascript 代码移动到 .js 文件后,它已修复。

标签: javascript jquery html


【解决方案1】:
function tableOpen(selInput)
{
    alert($(selInput).id().text()+"first");
    $('#user-table tr').unbind('click');
    $('#user-table tr').click( function() {
           alert($(selInput).id().text()+"second");
    });
    //some other function here from displaying the selected user to input field
}

【讨论】:

  • 每次点击tableOpenDOM 都会用ELEMENT附加点击事件
  • 非常感谢。你拯救了这一天。
  • 或者你可以在tableOpen之外使用$( "#user-table tr" ).on( "click", function() { //YOUR CODE });
【解决方案2】:

这是因为点击事件的多次绑定。 你可以在这里做两件事。

  1. 将点击绑定移出在绑定区域放置的块
  2. 在事件中使用关闭
$('#user-table tr').off('click').on('click', function() {
    alert($(selInput).id().text()+"second");
});

【讨论】:

    【解决方案3】:

    我不确定你到底想说什么,但我试过了,我收到了三个警报(等于 #user-table 中的行数)second

    $('#user-table tr').click( function() {
               alert($(selInput).id().text()+"second");
        });
    

    您必须使用特定的选择器来调用行上的click 事件。

    例如,为#user-table 中的每一行提供唯一的 ID,并使用它来调用 .click()

    【讨论】:

      最近更新 更多