尝试将 EventListener 添加到动态创建的对象

Trying to add EventListener to dynamically created object

我正在尝试从外部文件加载 HTML。然而,在这样做时,输入元素是不可交互的。我已经尝试使用 vanilla JavaScript 进行此操作但无济于事,只是导入了 jQuery。我目前的进度如下:

我有一个包含静态元素和菜单栏的页面。单击菜单栏图标时,元素内容会通过 JS/JQ 更新。这是我用于加载视图的 HTML 和 jQuery:

settings.html:

<section class="settings">
<div class="container">
    # some elements here

    <div id="graph-settings" class="settings-card">
        <i class="fa fa-chart-line fa-3x"></i><h1>Graph Settings</h1>
        <p>Web Interface Refresh Rate</p>
        <form>
            <input type="text" name="graphInterval" id="graphInterval" placeholder="E.g. 2000">
        </form>
    </div>

    # more elements here
</div>
</section>

jQuery:

$.get("./pages/settings.html", (data) => {
    $("#main").append(data);
});

$(document).on("click", "#graphInterval", function() {
    // do something...
    console.log("test");
});

内容似乎已正确加载到页面中,但不是 markable/interactable(动态添加到 DOM 等)。但是我的 jQuery 似乎没有找到 #graphInterval 元素,因为我没有从控制台获得任何记录输出。

任何使输入字段正常工作的方法都是一种解决方案。他们所需要的只是编辑和检索它的价值。稍后我将使用 JavaScript 到 add/interact 和按钮,不会使用发布表单,因此表单没有 "action=''".

如果在侦听器中使用 event delegation (where you set the event listener at a high level DOM object and let all events triggered from decedents of that high level element bubble up to the high level element, any new elements added in will trigger events caught higher up. Then, in the listener, you can check to see which element actually triggered the event and act accordingly. So, in your case, remove the id from the .on() method call and then check the event.target

// Set the event listener on a high level element and capture the event
$(document).on("click", function(event) {
    // You can find out what exact element triggered the event with event.target
    console.log("event triggered by: " + event.target);
    
    // Now you can proceed as you need to:
    if(event.target.id === "heading1"){
      console.log("You clicked the heading");
    } else if(event.target.id === "para1"){
      console.log("You clicked the paragraph");
    }
});


// Create new elements
let data1 = "<h1 id='heading1'>Some new data (click me)</h1>";
let data2 = "<p id='para1'>Some new data (click me)</p>";

// Dynamically add elements to document
$(document.body).append(data1);
$(document.body).append(data2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>