2017-08-26 30 views
2

這也許是非常基本的jQuery語法,但我對它不是很熟悉。我只想在頁面上存在具有特定標識的html輸入時才進行jquery ajax調用。我該怎麼做呢?有條件的ajax調用

回答

2
    你的腳本標記後包括
  1. 製作舒爾驗證(例如在關閉</body -tag之前)或等待文檔準備好DOM事件。
  2. 檢查DOM元素的存在。

$(document).ready(function() { 
 
    if ($('#jepp').length) { // 0 validates falsy and != 0 truthy 
 
     $('#jepp').val('do your stuff eg ajax') 
 
    } 
 
}); 
 

 
// or a little bit more advanced 
 
$(function() { // document ready 
 
    if (document.getElementById('jepp')) { // vanilla JavaScript but still straight forward 
 
     $('#jepp').val($('#jepp').val() + ' | a bit more advanced') 
 
    } 
 
})
<input id="jepp" value="" style="width:100%"> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

[truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)和 [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy ) – Axel

1

您可以檢查是否存在頁面上用id的元素,使用的selector.If長度是,執行您的請求

if($("#yourId").length>0){ 
    //Your request 
    $.post("ajax/test.html", function(data) { 

    }); 
} 
+0

長度將爲零它不存在。 – ste2425

2
<input name="foo" id="data"> 
<script type="javascript"> 
    ... 
     var elementSize = $('#data').size(); 
     if(size > 0){ 
      $.ajax({ 
       ... 
      }); 
      // Page contains id 
     }else { 
      //Page doesn't contains id 
     } 
    ... 
</script> 

你可以做到這樣。

$('#element-id').size()$('#element-id').length

是id元素的尺寸。 Id值必須是1並且是唯一的。你檢查大小,並讓阿賈克斯呼籲