jQuery如何在元素上单击隐藏只有与元素关联的li而不是其他元素

时间:2011-04-29 17:11:49

标签: jquery css ajax

我遇到了一些问题。基本上我通过名为notice.php的文件将通过jQuery中的加载函数加载的图像添加到页面中

此文件将显示照片等。我面临的问题是:对于照片,我将添加thickbox支持,我可以使用rel标签。但是,我希望通过单击将显示的图标,让我的用户能够删除这些照片。结构如下:

e
<ul class="imglist">

<li>
<img src="http://localhost/fileserver/3/2lV2H075.jpg" width="308" height="auto"    alt="Image1" />

<div class="actions">   
<a href="#" class="imglistbutton">
<img src="http://localhost/fileserver/1/j5357n7X.png" width="16" height="16" alt="Delete" />
</a>
</div>

</li>

<br/>

<li>
<img src="http://localhost/fileserver/3/2lV2H075.jpg" width="308" height="auto"    alt="Image2" />

 <div class="actions">  
 <a href="#" class="imglistbutton">
 <img src="http://localhost/fileserver/1/j5357n7X.png" width="16" height="16" alt="Delete" />
 </a>
 </div>

 </li>

 <br/>
 </ul>

所以当用户点击

  

      &lt; #img src =“http://localhost/fileserver/1/j5357n7X.png”width =“16”height =“16”alt =“删除”/&gt;       

jQuery代码将关闭单击此元素的特定LI标记。

以下是我失败的代码:

 <script type="text/javascript">
$(document).ready(function() {

$(".imglistbutton").live("click", function() {

$(this).hide();
var imgHide = $(this).attr("li")
$("img").hide();
$(imgHide).hide();

});
});
</script>

我的最后一个问题是:

基本上我有一个名为main.html的文件。当用户单击导航中的任何内容时,它会通过jQuery load命令将页面加载到指定的div id元素中。

所以说我点击“仪表板”。 PHP将加载dashboard.php,但我需要通过AJAX将更多项目加载到dashboard.php。

我尝试将代码放在main.html中,因此它将读取dashboard.php中的div元素并加载其他文件,方法与通过jQuery加载加载dashboard.php相同,但这似乎不起作用。我需要在每个其他文件中使用以下代码,然后使用main.html通过AJAX加载内容:

    <script type="text/javascript">

$(function() {
    var href = "notice.php";
    $("#dashboard_notice_utm").load(href);
});

</script>

因此,此代码将在dashboard.php中加载notice.php文件。是否有更简单的方法来实现这一点,而不必在页面中包含内容,而是使用一个JS文件代替?我的第一个问题也是如此,因为它需要在notice.php上的代码来关闭图像。

  • 提前谢谢你,抱歉这么长的问题。

4 个答案:

答案 0 :(得分:0)

对于第一个问题,您不想使用.attr("li"),因为li不是属性,它是祖先。你应该改为使用.closest:

$(".imglistbutton").live("click", function() {

$(this).closest("li").hide();

});
});

对于第二个问题,您可以使用load的完整参数在加载操作完成后执行jquery。像这样:

$('#result').load('dashboard.php', function() {
    var href = "notice.php";
    $("#dashboard_notice_utm").load(href);
});

这样,一旦加载了dashboard.php,就会调用notice.php加载到#dashboar_notice_utm。

答案 1 :(得分:0)

对于图片问题,<a>标记中没有属性“li”,因此我假设您只想隐藏整个<li>容器。在那种情况下

$(".imglistbutton").live("click", function() {

$(this).hide();
var imgHide = $(this).parents("li");
$("img").hide();
imgHide.hide();

});

应该有效

对于其他人,我建议您在SO上创建一个新问题,因为如果这是一个单独的问题,您将更有可能得到答案。

答案 2 :(得分:0)

我可能会使用1.3中引入的最近的父(.closest()),因为它更具体......

$(document).ready(function(){    
    $(".imglistbutton").live("click", function(){
        var imgHide = $(this).closest("li"); // closest parent li only
        imgHide.hide(); // hides all children (this, div, a, img, etc.)
    });
});

答案 3 :(得分:0)

回答第一个问题

$('.imglistbutton').live('click', function() {
  $(this).closest('li').hide();
});

将找到与所单击图像最接近的li链接

第二个问题

我要么在主页面中拥有它 - 也就是说,如果你的框架允许它,或者在头部使用脚本标记在每个页面上包含一个单独的js文件。