jQuery对话框选择器没有响应用Ajax加载的元素的类名

时间:2014-03-10 21:52:32

标签: jquery ajax jquery-selectors jquery-ui-dialog class-attribute

更新:问题已解决:

由于在页面加载之后创建了“有问题的”元素,因此事件委托确保所有这些元素都绑定到jQuery事件。

原帖:

我得到了这段代码:

while ($row=mysqli_fetch_array($res)){
    if($cont>3){
       $cont=1;
       $txt=$txt.'</tr><tr>';
    }
    $txt=$txt.'<td>'; 
    $txt=$txt.'<figure><img src="'.$row['picture'].'"/></figure>';
    $txt=$txt.'<figcaption>'.$row['pictureDesc'].'</figcaption>'; 
    $txt=$txt.'<div class="dialogInfoOpener" style="border:solid red 1px;">Details</div>'; 
    $txt=$txt.'</td>';    
    $cont++; 
}   
$txt=$txt.'</tr>';
echo $txt;

它是PHP文件的一部分,它与JS文件(Ajax)一起工作,以便通过连接字符串按3行单元格“构造”一个​​表。对于每个单元格,从数据库加载一些数据。每个单元格都会为div添加给定类dialogInfoOpener)和某些内联样式。应单击div元素以打开jquery对话框 - 这是问题开始的地方。

我的对话框的代码:

HTML

<div id="dialogInfo" title="Product description">Info to be put in here.</div>

的jQuery

$("#dialogInfo").dialog({ 
    autoOpen: false,
    buttons:[{
        text: "Close", click : 
        function(){
            $(this).dialog("close");
        }
    }]
});


$(".dialogInfoOpener").click(function(event){</s>
    $("#dialogInfo").dialog("open");</s>
});</s>

代码可以很好地用于页面上找到的具有类dialogInfoOpener的任何元素,属于的 div元素的 EXCEPT 刚建成的桌子。单击这些div时,它不会执行任何操作(为每个单元格正确设置类和样式属性)。似乎jQuery没有响应给div的类名。为什么呢?

我希望很清楚。

我很感激任何有用的建议。

3 个答案:

答案 0 :(得分:1)

由于这些元素是动态创建的,您可以使用event delegation,例如:

$(document).on("click", ".dialogInfoOpener", function(event){
    $(".dialogInfo").dialog("open");
});

通常使用比document更好的选择器 - 找到.dialogInfoOpener元素的一致父元素并使用它。

此外,我认为您可能有拼写错误 - 您的HTML提到#dialogInfo元素,但在您的点击功能中使用.dialogInfo?请记住,ID必须是唯一的,如果您有多个ID,只需使用一个类。

答案 1 :(得分:0)

重新运行在Ajax调用完成后连接click事件的代码。尝试取消绑定/绑定,这样就不会触发重复事件。

答案 2 :(得分:0)

你混合了Ids和Classes。

$("#dialogInfo").dialog({使用ID但$(".dialogInfo").dialog("open");使用了一个类。如果你这些相同,你就可以解决它。