2013-02-08 114 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>