jquery - 有条件的ajax调用

标签 jquery html ajax

这也许是非常基本的jquery语法,但我不太熟悉它。我想仅当页面上存在具有特定 id 的 html 输入时才进行 jquery ajax 调用。我该怎么做?

最佳答案

  1. 确保您的脚本包含在要验证的标记之后(例如,在结束 </body -标记之前)或等待文档就绪 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>

关于jquery - 有条件的ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899398/

相关文章:

javascript - 在 jQuery 中绑定(bind)动态创建的元素

jquery - 如何创建固定的垂直导航?

javascript - 将小型网络应用程序从普通网站迁移到 WordPress 网站?

html - CSS 网格自动流 : dense not working

javascript - 使用 Laravel 添加数据 JavaScript

php - Valums 文件 uploader : Limit uploads by users credit

javascript - 下拉菜单关闭掉 Angular 图标

jquery - 固定导航工作一次然后中断

html - 为什么这些具有完全相同类的按钮具有不同的宽度?

javascript - 使用post方法将值从一个html传递到另一个html