2013-02-08 81 views
0

我在写一个PHP程序,显示用户的待办事项列表。我所拥有的基本上是一个无序列表,它有一个复选框,当选中时,它将允许用户将列表项标记为完成(即给文本一个删除线)。下面是我对名单如何在外部jquery.js文件中获取PHP迭代变量?

echo '<ul>'; 

for ($i=0; $i<6; $i++){ 

     $text = "This is item number " . $i; 
     $complete = 'No'; 
     $order = 'This item is to be done #' . $i; 

     echo '<li id = '. $i . '>'; 

    echo 'Item complete? <input type="checkbox" id="checkbox" />'; 
    echo '<span id = ' . $i . ' onLoad="crossOut()">Item: ' . $text . ' Complete? ' .$complete . '&nbsp&nbspWhen to do Item: ' . $order . '</span>'; 
    echo '</li>'; 

     } 

echo '</ul>'; 


} 

而且这里的代码是我在使用

$(document).ready(function crossOut(){ 
    $("#checkbox").change(function crossOutText(){ 
     if($(this).is(":checked")){ 
      $("#liID").css("text-decoration", "line-through"); 
     } 
    }) 
}) 

我试图找出是如何通过从PHP列表ID为jQuery函数jquery函数,在外部的JS文件中,以便每当用户检查一个项目时,它会标记该项目已完成,并在该项目的文本上添加删除线。我是新来的使用jQuery和任何人都愿意给任何帮助将不胜感激。

回答

3
$(document).ready(function(){ 
    $("input:checkbox").change(function(){ 
     if($(this).is(":checked")){ 
      $(this).parents("li").css("text-decoration", "line-through"); 
      // ^^^^^^^^^^^^^^ strike through the parent list item. 
     } 
    }) 
}) 

下面是一个使用CSS类有更好的方式:

$(document).ready(function(){ 
    $("input:checkbox").change(function(){ 
     $(this).parents("li").toggleClass('strike', this.checked) 
     // ^^^^^^^^^^^^^^ strike through the parent list item. 
    }) 
}) 

CSS:

.strike { 
    text-decoration: line-through; 
} 

演示:http://jsfiddle.net/maniator/unmLd/


Disclamer:
我在这两个例子改变#checkbox到,因为你不能具有相同ID的多个元素! 尝试使用类代替。

此外,删除代码的crossout()一部分......它没有做任何事情,可能你的页面上抛出一个错误...

+0

我试过在我的代码中测试第二种方法,但由于某种原因,它不工作。可能有些简单的事情,我已经完成了,我失踪了。这正是我期待的。 – 2013-02-08 13:55:05

+0

不知道...使用生成的HTML制作小提琴... – Neal 2013-02-08 13:55:50

+0

乐意帮忙@AaronKlassen^_ ^ – Neal 2013-02-08 13:56:10

0

像这样的事情?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script type="text/javascript" src="js/jquery.js"></script> 
<script> 
$(document).ready(function(){ 
    $('input[type="checkbox"]').change(function(){ 
     if($(this).is(":checked")){ 
      $(this).parent().css("text-decoration", "line-through"); 
     }else{ 
      $(this).parent().css("text-decoration", "none"); 
     } 
    }); 
}); 
</script> 
<title>Untitled Document</title> 
</head> 

<body> 

<?php 
    echo '<ul>'; 
    for ($i=0; $i<6; $i++){ 
     $text = "This is item number " . $i; 
     $complete = 'No'; 
     $order = 'This item is to be done #' . $i; 
     echo '<li id = '. $i . '>'; 
     echo 'Item complete? <input type="checkbox" id="checkbox" />'; 
     echo '<span id = ' . $i . '>Item: ' . $text . ' Complete? ' .$complete . '&nbsp&nbspWhen to do Item: ' . $order . '</span>'; 
     echo '</li>'; 
    } 
    echo '</ul>'; 
?> 

</body> 
</html>