让jquery脚本按预期工作的问题

时间:2011-02-11 13:56:43

标签: javascript jquery javascript-events onclick

我是jquery的新手。我想要一个简单的清单。我只是想显示和隐藏其他细节。

<ul>
  <li><div onclick="show()"><img src="product_pic" />Product 1</div><div id="details" class="hide">short intro about the product</div></li>
<ul>  

css

.hide {display: none;}

jquery

function show(){
     $(this).next().toggleClass('hide');
}

它不起作用。我感谢任何帮助。

感谢。

2 个答案:

答案 0 :(得分:5)

两件事:

  1. 它是toggleClass,而不是toggleclass
  2. 使用jQuery连接事件处理程序,而不是使用旧式属性。
  3. 所以:

    $("div.hide").prev().click(function() {
        $(this).next().toggleClass('hide');
    });
    

    Live example

    如何运作:

    • 我们找到具有“隐藏”类的div,然后我们通过prev找到所有直接前辈。这会创建一组所有的div,紧跟着div.hide div。
    • 我们将click事件挂钩在前辈身上。
    • click发生时,我们会在点击的元素后切换next元素上的类。

    我想我建议您使用单独的“详细信息”类或“隐藏”旁边的内容,以防您想要在其他不具备此精确结构的地方使用“隐藏”。如果你这样做,你可以在不改变课程的情况下展示和隐藏; jQuery的智能足以覆盖CSS“display:none”位,即使是由规则应用(并非所有的lib都是)。这看起来像这样:

    CSS:

    .details {
        display: none;
    }
    

    标记:

    <li><div><img src="product_pic" />Product 1</div><div class="details">short intro about the product</div></li>
    

    JavaScript的:

    $("div.details").prev().click(function() {
      $(this).nextAll("div.details:first").toggle();
    });
    

    Live example

    请注意,使用toggle而不是toggleClass


    旁注:我们注意到id="details"的详细信息div。请注意,id必须是唯一的,因此如果您有多个值,则不能将“详细信息”用作每个值的id。< / p>

答案 1 :(得分:0)

1。更改“toggleClass”的“toggleclass” 2。你可以试试这个:

HTML:

<ul>
  <li>
      <div class="show"><img src="product_pic" />Product 1</div>
      <div id="details" class="hide">short intro about the product</div>
  </li>
<ul>

JS:

$('.show').bind('click', function(ev){
     $(this).next('div').toggleClass('hide');
});

CSS

.hide {display: none;}

修改

如果您要使用多个标签“li”,则应删除ID“详细信息”,因为它会重复,并且必须是唯一的。您的HTML代码可能是下一个:

HTML:

<ul>
  <li>
      <div class="show"><img src="product_pic" />Product 1</div>
      <div class="details hide">short intro about the product</div>
  </li>
  <li>
      <div class="show"><img src="product_pic" />Product 2</div>
      <div class="details hide">other short intro about the product</div>
  </li>
<ul>

OR

<ul>
  <li>
      <div class="show"><img src="product_pic" />Product 1</div>
      <div id="details-prod-1" class="hide">short intro about the product</div>
  </li>
  <li>
      <div class="show"><img src="product_pic" />Product 2</div>
      <div id="details-prod-2" class="hide">other short intro about the product</div>
  </li>
<ul>