我对web开发相当陌生,所以我不确定这是否是完成这项任务的最有效的方式。
我目前正在写一个网上商店,在产品页面上,我有x数量的产品从数据库后端获取。然后,我使用结果数组生成动态html/css,以便输出:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo('
<div class="box">
<div class="product"><img src="upload/' . $row['prod_image'] . '" /></div>
<h3> ' . $row['prod_title'] . '</h3>
<div class="create-user">
<p>More Details...</p>
</div>
<div class="dialog" title="Basic dialog">
<p><img src="upload/class.png"/>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the x icon.</p>
</div>
<p class="price">Price: <span class="red">£' . $row['prod_price'] . '</span></p>
<div><a href="#"></a> <a href="#"><img src="images/addtocart.gif" border="0" /></a></div>
<div class="clearfloat"></div>
</div>'
);
}现在,当你点击"more details“时,它应该为每个特定的产品调用对话框函数,以便打开”jQuery“标签,但这似乎只适用于第一个产品,而不适用于其他产品。
JS代码:
$(function() {
$( "#dialog").dialog({
autoOpen: false
});
$('#create-user').click(function() {
$('#dialog').dialog('open');
});
});我设法绕过了这一点,但这似乎是一种肮脏的方式,这就是我所做的。我为每个产品添加了一个唯一的div id,然后使用增量使它们与JavaScript保持一致:
$incr = 1;
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo('
<div class="box">
<div class="product"><img src="upload/' . $row['prod_image'] . '" /></div>
<h3> ' . $row['prod_title'] . '</h3>
<div id="create-user' . $incr . '">
<p>More Details...</p>
</div>
<p class="price">Price: <span class="red">£' . $row['prod_price'] . '</span></p>
<div><a href="#"></a> <a href="#"><img src="images/addtocart.gif" border="0" /></a></div>
<div id="dialog' . $incr . '" title="Basic dialog">
<p><img src="upload/class.png"/>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the x icon.</p>
</div>
<div class="clearfloat"></div>
</div>'
);
$incr++;
}以及与之配套的JS:
$(function() {
var diag_num = 0;
while(diag_num < 4) {
diag_num +=1;
$("#dialog" + diag_num ).dialog({
autoOpen: false
});
$('#create-user' + diag_num).click(function() {
$('#dialog' + diag_num).dialog('open');
});
}
});虽然这种方法适用于每页固定数量的产品,而且这种方法没有问题,因为我每页只有10个左右(所以我知道我的变量长度),但我不禁认为这是一种糟糕的方式。
我还研究了使用"div class",然后将所有产品分配到同一个类,使用jQuery类选择器找到"create-user“类,然后使用"parent”方法向上爬回DOM树以找到下一个"dialog“类。这是可行的,但当您打开一个对话框时,它会在页面上为每个产品打开一个,因此我认为"DIVS“是唯一的。
我希望这是有意义的。
发布于 2013-02-19 16:09:25
$('.create-user').click(function(){
$(this).siblings('.dialog').dialog('open');
});这应该适用于您发布的第一个代码示例。
单击时,它会选择下一个带类的项目对话框并打开它。
这里的$(this)代表点击的"More Details...“。siblings()获取所有的同级,如果你添加了一个选择器,它会根据给定的选择器过滤它们。由于您已将项目包装在一个框中,因此不应选择任何其他对话框。
https://stackoverflow.com/questions/14940340
复制相似问题