2014-01-21 36 views
0

我有以下代碼。它應該是自我記錄。Negator僞類不工作

 $('body:not(#name)').click(function() { 
      if (document.getElementById('name').value === '') { 
       document.getElementById('name').value = 'Anonymous'; 
      } 
     }); 

否定符被忽略。我做錯了什麼?


編輯:我嘗試了所有建議的解決方案,但沒有運氣。可能是因爲#name是輸入文本字段?代碼在上下文中,並與我的最後一次嘗試。不帶痕跡():

<form action="process-comment.php" method="POST"> <br/> 
     Name: <input type"text" id="name" name="name" value="Anonymous"> <br/> 
     E-mail: <input type"text" id="email" name="email" value="Secret"> <br/> 
     Comment: <input type"textarea" id="comment" name="comment"> <br/> 
     <input id="submitbutton" type="submit" value="Send"> 
    </form> 

    <script> 
     $(document).ready(function() { 


      $('#name').click(function() { 
       if (document.getElementById('name').value === 'Anonymous') { 
        document.getElementById('name').value = ''; 
       } 
      }); 

      $('#email').click(function() { 
       if (document.getElementById('email').value === 'Secret') { 
        document.getElementById('email').value = ''; 
       } 
      }); 

      $('body').not('#name').click(function() { 
       if (document.getElementById('name').value === '') { 
        document.getElementById('name').value = 'Anonymous'; 
       } 
      }); 

      $('body').not('#email').click(function() { 
       if (document.getElementById('email').value === '') { 
        document.getElementById('email').value = 'Secret'; 
       } 
      }); 

我想要的文本區域顯示「匿名」和「祕密」直至被點中。當用戶點擊其他地方時,值爲「」,表示沒有任何輸入,我想要「匿名」和「祕密」返回。目前,這些字段已被清空,但點擊後立即填充。

+1

如果您的代碼符合您的想法,那麼您的代碼只能自我記錄。請不要依賴代碼在這裏不言自明;我們需要知道你的意圖*。你是否想要找到'body'中包含的不是'#name'的所有元素,還是隻有當它自己的ID不是'name'時纔想匹配'body'元素? – meagar

回答

0

你的選擇是錯誤的,應該是:

$('body :not(#name)') 

或者更好:

$('body').find(':not(#name)') 
0

檢查下一個代碼。

$('body').click(function() { 
    if ($(this).find('#name').val() === '') { 
     $(this).find('#name').val('Anonymous'); 
    } 
}); 
0

jQuery有2個沒有選擇,你可以從

:not
$選擇(的身體:不(#NAME)「)等等

.not
$('body')。not('#name')。etc ...