【问题标题】:Why isn't my element being added to the page? [closed]为什么我的元素没有添加到页面中? [关闭]
【发布时间】:2022-01-25 04:57:38
【问题描述】:

我想使用 jQuery 在 DOM 树上添加一个 type=text 属性的输入元素。但是,它似乎不起作用。 DOM 树是一样的,没有控制台错误。

$(document).ready(function() {
  var $code = $("#command");
  var $text = $("#itemtext");
  var $count = $('#count');
  var $add = $('add');

  $add.click(function() {
    $("#items").last().after('<input type="text" id="itemtext" />');
  });
  $("#generatebutton").click(function() {
    $code.text('/give @p bundle{Items:[{id:' + $text.val() + ',Count:' + $count.val() + '}]}');

  });
});
<body>
  <h1 id="title">Bundle Generator for mc</h1>
  <div id="items">
    <input type="text" placeholder="item name" id="itemtext">
    <input type="number" min="-128" max="127" id="count">
    <button id="addslot">Add slot</button>
    <button id="generatebutton">Generate!</button>
  </div>
  <h2>Your command is here!</h2>
  <p id="command"></p>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>

这一行:

$("#items").last().after('<input type="text" id="itemtext" />');

没有用,谁能帮帮我?

【问题讨论】:

  • 这里没有.append
  • 你为什么要运行这么古老的jQuery版本?您可能可以毫无问题地更新到 3.x。
  • last()$('#items') 上毫无意义,因为永远只有一个。
  • $('add') 不会选择任何内容,因为页面中没有 add 元素。
  • 错字:var $add = $('add'); 应该是var $add = $('#addslot');

标签: javascript jquery


【解决方案1】:

您提到了不在 DOM 中的 id。也许您正在寻找addslot 而不是addvar $add = $('add') 中也没有 id ('#') 的指示。

$(document).ready(function() {
  var $code = $("#command");
  var $text = $("#itemtext");
  var $count = $('#count');
  var $add = $('#addslot');

  $add.click(function() {
    $("#items").last().after('<input type="text" id="itemtext" />');
  });
  $("#generatebutton").click(function() {
    $code.text('/give @p bundle{Items:[{id:' + $text.val() + ',Count:' + $count.val() + '}]}');

  });
});
<body>
  <h1 id="title">Bundle Generator for mc</h1>
  <div id="items">
    <input type="text" placeholder="item name" id="itemtext">
    <input type="number" min="-128" max="127" id="count">
    <button id="addslot">Add slot</button>
    <button id="generatebutton">Generate!</button>
  </div>
  <h2>Your command is here!</h2>
  <p id="command"></p>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多