2013-04-21 171 views
-5

我想通過將文本轉換爲文本字段來編輯文本。我只是想嘗試在我的瀏覽器,所以我複製並粘貼在Dreamweaver中,但它不工作:JavaScript代碼不起作用

,你可以在這裏找到:http://jsfiddle.net/cnuDh/

,但它不工作

的代碼如下

<label id="edit" style="cursor:pointer; color:blue;"> 
    edit 
</label> 
<table> 
    <tr> 
     <td>First Name:</td> 
     <td>John</td> 
    </tr> 
    <tr> 
     <td>Last Name:</td> 
     <td>Wright</td> 
    </tr> 
</table> 
<script type="text/javascript" charset="utf-8"> 
$('#edit').click(function() { 
    var $table = $('table'); 
    if ($table.find('input').length) return; 
    $table.find('td:nth-child(2)').html(function (i, v) { 
     return '<input value=' + v + '>'; 
    }) 
}) 
$('table').on('blur', 'input', function() { 
    $('table input').replaceWith(function() { 
     return this.value; 
    }) 
}) 
</script> 

任何幫助,請

+0

即使我有麻煩語法..如果你使用Firefox,你可以使用一個名爲「螢火蟲」,當他們出現錯誤,會告訴你的JavaScript錯誤的工具安慰。 – Silvertiger 2013-04-21 09:35:15

+7

你把jquery添加到你的頁面了嗎? – 2013-04-21 09:37:24

+0

請提一下你面對的錯誤 – 2013-04-21 09:47:48

回答

0
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>                 

編輯

<table> 
<tr><td>First Name: </td> 
    <td>John</td> 
</tr> 
<tr><td>Last Name: </td> 
    <td>Wright</td> 
</tr> 

$('#edit').click(function() { 
    var $table = $('table'); 
    if ($table.find('input').length) return; 
    $table.find('td:nth-child(2)').html(function(i, v) { 
    return '<input value=' + v + '>'; 
    }) 

    }) 


$('table').on('blur', 'input', function() { 
$('table input').replaceWith(function() { 
    return this.value; 
}) 
}) 
+0

代碼是好的,對我來說它工作。 – 2013-04-21 09:49:05

+0

應該注意那些雙向正斜槓。 – Oleg 2013-04-21 09:54:25

+0

它仍然不起作用:( – Mercury121 2013-04-21 09:57:30

1

不要忘記的jQuery的DOM加載添加到頁面中,以能夠使用其選擇以及$(document).ready()儘快加載腳本和網頁內容之前被加載。

<!DOCTYPE html> 
<html> 
    <head> 
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function(){ 
     $('#edit').click(function() { 
      var $table = $('table'); 
      if ($table.find('input').length) return; 
      $table.find('td:nth-child(2)').html(function(i, v) { 
      return '<input value=' + v + '>'; 
      }) 
     }) 
     $('table').on('blur', 'input', function() { 
      $('table input').replaceWith(function() { 
      return this.value; 
      }) 
     }) 
     }); 
    </script> 
    </head> 
    <body> 
    <label id="edit" style="cursor:pointer; color:blue;">edit</label> 
    <table> 
     <tr><td>First Name: </td> 
      <td>John</td> 
     </tr> 
     <tr><td>Last Name: </td> 
      <td>Wright</td> 
     </tr> 
    </table> 
    </body> 
</html> 
+0

哇哇哇謝謝..其工作 – Mercury121 2013-04-21 10:00:59

+0

沒問題!需要讓你的基礎知識正確別忘了標記我的答案,如果它讓你成爲一個快樂的人! – 2013-04-21 10:06:47

2

添加jQuery庫

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>