簡體   English   中英

.append()到JS使用.on('click')創建的元素

[英].append() to JS created element with .on('click')

當用戶輸入一個字符串時,每個字符將被拆分為一個數組,並顯示為“行”, 如下所示 但是,在JS生成的元素上使用click事件處理程序時,它不會追加到被單擊的div上,而是追加到#node_list上 如何附加到單擊的div?

HTML

<input id='input' type='text'></input>
<button id='parse_seq' type="button">Parse</button>
<div id='node_list'></div>

JS

// Fetch input
var inseq = $("#input").val()

// Split each input character into array
var seqarr = inseq.split("")

// Loop over array to create div for each character
for (var i = 0, len = seqarr.length; i < len; i++) {

    // Prepend button to list
    if (i == 0) {
        CreateNewButton(i)
    }

    // Add node
    CreateNode(i+1,seqarr[i].toUpperCase())

    // Add button
    CreateNewButton(i+1)
}

// Create div
function CreateNode(id,content) {
    $("#node_list").append("<div id='seq_node" + id + "' class='seq_node'><span class='node_id'>" + id + "</span><span class='node_content'>" + content + "</span></div>")
}

// Create new button
function CreateNewButton(id) {
    $("#node_list").append("<div id='new_node" + id + "' class='new_node'>+</div>")
}

$('#node_list').on('click', '.new_node', function() {
    $(this).append(CreateNode(1,"new"))
    $(this).append(CreateNewButton(1))
})

您可以修改函數以接收元素作為參數。 然后只需附加到該參數即可。 例如:

// Create div
function CreateNode(id,content, node) {
    node.append("<div id='seq_node" + id + "' class='seq_node'><span class='node_id'>" + id + "</span><span class='node_content'>" + content + "</span></div>")
}

// Create new button
function CreateNewButton(id, node) {
    node.append("<div id='new_node" + id + "' class='new_node'>+</div>")
}

然后,當您調用函數時:

$('#node_list').on('click', '.new_node', function() {
    CreateNode(1,"new", $(this))
    CreateNewButton(1, $(this))
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM