我正在为一个网站重新设计,现在我的目标是用新窗口(jQuery)替换打开某个窗口的旧方法。这是它以前的样子:https://i.stack.imgur.com/WGp5R.png 这就是现在的样子:https://i.stack.imgur.com/ZxSxx.png.一切看起来都不错,但有一个问题。jQuery对话框仅适用于每个页面中的第一项,如果我按第一项以外的其他项,则没有任何反应。此外,如果我继续打开 jQuery 对话框,它会开始逐个显示页面中的所有项目(例如:我按下第一项,它会打开包含第一项内容的 jQuery 对话框,我再次按下第一项,但现在它显示第二项的内容,依此类推, 出于某种原因,它一一显示它们)。
该 php 代码:
// SHOP ITEM LARGE
//This is how it worked before
// print '<a href="';
// print "javascript:regular('pages/item_large.php?shop=".$item->webshopMenu."&nr=".$item->id."');";
// print '"><img style="margin-top:5px;margin-bottom:0; padding-bottom:0px;" border="0" src="'.$img.'" alt="'.$item->Naam.'" '.$image_size.'></a>';
// print '<br><small>Artikelnr. : '.$item->Artikelnr.'</small></div>'."'n";
//This is how I'm trying to do it now
print '<a id="save" href="';
print '"><img style="margin-top:5px;margin-bottom:0; padding-bottom:0px;" border="0" src="'.$img.'" alt="'.$item->Naam.'" '.$image_size . "</a>";
print '<br><small>Artikelnr. : ' . $item->Artikelnr . '</small></div>' . "'n";
?>
<div style="display: none" id="dialog">
<?php
echo "<iframe src='pages/item_large.php?shop=" . $item->webshopMenu . "&nr=" . $item->id . "'" . "width='100%' height='100%' frameborder='0'></iframe>"
?>
</div>
j查询代码:
(function() {
$('#save').click(function(event) {
event.preventDefault();
$('#dialog').dialog({
modal: true,
scrollable: false,
draggable: false,
resizable: false,
width: 450,
height: 445
})
})
})();
任何想法为什么会发生这种情况?
这只是因为您不能使用相同的id
创建多个 HTML 项目并期望它起作用。给他们不同的id
或使这个CSS类名基于
例如,您可以使第一个元素具有id="save1"
和第一个对话id="dialog1"
基于类的解决方案是:class="save"
链接和对话框class="dialog"
而不是id
。那么javaScript会像:
将<a>
和对话框div
放在同一节<div class="section">
中,以便它们可以具有相同的父元素。然后:
(function() {
$('a.save').click(function(event) {
event.preventDefault();
$(this).parents(".section:first").find(".dialog").dialog({
modal: true,
scrollable: false,
draggable: false,
resizable: false,
width: 450,
height: 445
})
})
})();
使用类而不是 id。 对"保存"按钮(如"class="saveBtn"
")使用类,对对话框(如"class="dialog"
")使用类。然后将"保存"按钮和对话框包装在具有类似 class="section"
的类的容器中。 然后你可以利用jQuery的潜力来查找彼此相对的元素,如下所示:
$('.saveBtn').on('click', function(e) {
e.preventDefault();
var dialog = $(this).closest('.section').find('.dialog'); // this will find the dialog that is in the same section as the save button you just clicked on.
//then you do whatever else of the code you want here.
});
此解决方案允许您编写更清晰的代码,而无需尝试管理 ID 和随机索引以获得正确的对话框。