检查跨度并删除第一个孩子

时间:2012-11-04 22:40:49

标签: javascript jquery cycle html

基本上,这会在点击时进入下一个隐藏的范围。

标记:

<div id="facts">
    <span>click to cycle</span>
    <span>fact 1</span>
    <span>fact 2</span>
    <span>fact 3</span>
    <span>fact 4</span>
</div>

js:

$(document).ready(function() {
    var current = 1;
          $('#facts span').click(function() {
              // Hide all of them
              $('#facts span').hide();
              // Unhide the current one:
              $('#facts span:eq(' + (current % $('#facts span').length) + ')').show();
              // Increment the variable
              console.log(current % 4);
              current++;
          });

    // Unhide the first one on load
    $('#facts span:first-child').show();
});​

我现在要做的是在点击后删除第一个跨度,因为用户无需再次看到“click to cycle”指令。

2 个答案:

答案 0 :(得分:1)

将特定ID分配给原始ID,将类分配给其他ID。

<span id='removeme'>click to cycle</span>
<span class='cycleme'>fact 1</span>
<span class='cycleme'>fact 2</span>
<span class='cycleme'>fact 3</span>
<span class='cycleme'>fact 4</span>

显示removeme并通过CSS隐藏所有其他

#removeme {
  display: inline;
}
span.cycleme {
  display: none;
}

在脚本中,将单击事件绑定到原始事件以简单地将其删除。随后的处理程序将获得与之前相同的处理程序。

$(document).ready(function() {
    // Initialize
    var current = 1;

   // Bind the first one's onclick to remove itself
   $('#removeme').click(function() {
      $(this).remove();
      // And display the first one
      $('#facts span:first-child').show();
   });


   // Target the others via their class
   $('#facts span.cycleme').click(function() {
      // Hide all of them
      $('#facts span').hide();
      // Unhide the current one:
      $('#facts span:eq(' + (current % $('#facts span.cycleme').length) + ')').show();
      // Increment the variable
      current++;
   });
});​

Here is the live example

答案 1 :(得分:1)

你去吧

Fiddle

HTML

<div id="facts">
    <span id='remove'>click to cycle</span>
    <span>fact 1</span>
    <span>fact 2</span>
    <span>fact 3</span> 
   <span>fact 4</span>
</div> 

<强> JQuery的

$(document).ready(function() {
    var current = 1;
          $('#facts span').click(function() {
              $('#remove').remove();
              // Hide all of them
              $('#facts span').hide();
              // Unhide the current one:
              $('#facts span:eq(' + (current % $('#facts span').length) + ')').show();// Increment the variable
              console.log(current % 4);
              current++;
          });

    // Unhide the first one on load
    $('#facts span:first-child').show();
});