【问题标题】:Cannot set .attr("placeholder", "text") with jQuery无法使用 jQuery 设置 .attr("placeholder", "text")
【发布时间】:2016-04-20 10:21:53
【问题描述】:

我正在尝试在来自 PHP 请求的字段上设置占位符,但没有成功。这是我的代码:

<form>
 <div class="form-group">
   <?php do_action('register_form'); ?>
 </div>
 <button type="submit">Go</button>
</form>

在HTML中的输出代码如下:

<input type="password" name="cimy_uef_wp_PASSWORD" id="cimy_uef_wp_1" class="cimy_uef_input_27" value="" maxlength="100">

我正在尝试使用这个 jQuery 函数来选择它。它适用于控制台,但不适用于网站本身:

$( window ).load(function() {
  $( "#cimy_uef_wp_1" ).attr("placeholder","Password*");
});

【问题讨论】:

  • 代码works。表单是从一开始就存在于页面中,还是通过 AJAX 加载?
  • 我还检查了控制台中的代码并且它有效,但仅在控制台中。表单从一开始就没有出现在页面中。 PHP 使用来自外部 WordPress 网站的此请求生成它:

标签: jquery jquery-selectors attr


【解决方案1】:
$(document).ready(function(){ 
  $('form').find("#cimy_uef_wp_1").each(function(ev)
  {
      if(!$(this).val()) { 
      $(this).attr("placeholder", "Password*");
  }
  });
});

将此代码复制并粘贴到您的 js 文件中,这将更改整个站点的所有占位符文本。或者,添加 jQuery 使其在表单之后运行:

 <form>
   ...
 </form>
 <script>
    $( "#cimy_uef_wp_1" ).attr("placeholder","Password*");
 </script>

【讨论】:

  • oMiKey 感谢您的努力。您的代码在控制台中有效,但在网站中也无效。我认为问题是因为表单是使用 PHP 请求生成的。也许它在 jQuery 之后加载......我不知道。很奇怪的问题:(
  • 我认为您可能必须使用 php 添加占位符
  • 会很棒,但不幸的是我无法访问 PHP...需要找到一种使用 JS 的方法 :) 再次感谢您的努力!
【解决方案2】:

我假设您的 sw 使用 ajax 调用动态创建元素。如果是这种情况,并且 ajax 调用的全局选项未设置为 false,则可以使用类似:

$(document).ajaxSuccess(function(e, jqXHR, settings) { if ($("#cimy_uef_wp_1").length > 0) { // 元素准备好了 $("#cimy_uef_wp_1").attr("占位符","密码*"); } });

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2014-09-01
    • 2015-03-06
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多