簡體   English   中英

簡單的jQuery模糊功能無法正常工作

[英]Simple jQuery blur function not working

我有一個時刻,我無法得到一段簡單的代碼。 盡管花費了一個多小時,但我無法讓這段代碼工作;

<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo 'Test'; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"><!-- jQuery stylesheet -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script><!-- jQuery libary -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script><!-- jQuery UI -->
</head>
<body>

<script>
$("#target").blur(function () {

    alert("Handler for .blur() called.");

});
</script>

<form>
    <input id="target" type="text" value="Field 1">
    <input type="text" value="Field 2">
</form>

</body>
</html> 

我通過HTML 5驗證器運行我的代碼,以確保它不是一個愚蠢的東西,我已經確保我使用的是最新版本的jQuery。 奇怪的是,我可以讓代碼在jsFiddle上運行。

$(function(){

    $("#target").blur(function () {

        alert("Handler for .blur() called.");

    });
});

您需要將腳本更新為上面所寫的內容。 那就是添加一個包裝器。

您使用jquery綁定事件。 但是,當腳本執行時,沒有必要加載jquery,因此,綁定不會發生,因此,函數不會被觸發。

您需要添加一個jquery准備好的包裝器,這樣可以確保在dom准備就緒后完成所有事件綁定和腳本執行。

在這里,我為您創建了一個帶有工作版本的plunker - http://plnkr.co/edit/Xhur8f1ur194ii6XlRby?p=preview

將其添加到就緒功能中

 <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("input").blur(function(){ alert("This input field has lost its focus."); }); }); </script> </head> <body> Enter your name: <input type="text"> <p>Write something in the input field, and then click outside the field to lose focus (blur).</p> </body> </html> 

把函數放在document.ready中

<script>
$(document).ready(function(){
  $("#target").blur(function () {

    alert("Handler for .blur() called.");
  });
});
</script>

或者放置身體末端的腳本標簽

請將你的js代碼包裝進去

$(function(){

// your code 
});

這將是

  <script>
    $(function(){
      $("#target").blur(function () {
        alert("Handler for .blur() called.");
      });
    });
  </script>

這是參考https://api.jquery.com/ready/

您的JavaScript在呈現input元素之前正在運行,因此沒有任何內容可以將事件附加到。 將腳本移動到頁面末尾或將其包裝在$(function(){...}) 執行后者會使腳本在執行之前等待瀏覽器觸發的DOMReady事件。

選項1:

<body> 
  <form> 
    <input id="target" type="text" value="Field 1"> 
    <input type="text" value="Field 2"> 
  </form>
  <script> 
    $("#target").blur(function () {
      alert("Handler for .blur() called."); 
    }); 
  </script> 
</body>

選項2:

<body>
  <script> 
    $(function(){
      $("#target").blur(function () {
        alert("Handler for .blur() called.");
      }); 
    });
  </script> 
  <form> 
    <input id="target" type="text" value="Field 1"> 
    <input type="text" value="Field 2"> 
  </form>
</body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM