簡體   English   中英

如何在表格行上執行功能單擊 javascript/html

[英]How to perform a function on table row click javascript/html

我已經建立了一個返回 Ajax 結果的表,如下所示:

function searchUsers() {
    var searchText = (document.getElementById('searchInput').value)

    $.ajax({
    url : "https:" + "/" + "/downstreamaudio.com/SearchUsers.php",
    method : 'POST',
    data : {searchQuery: searchText},
    dataType: "json",
    success : function a(result) {
            console.log(result)

            console.log(result.length)

        var i;

        var table = document.getElementById("userSearchTableId");
        table.style.height = (result.length * 80 + "px")
        while(table.rows.length > 0) {
            table.deleteRow(0);
        }
    table.style.border = "0px solid black"

    for (i = 0; i < result.length; i++) {
             console.log(result[i].username);

            document.querySelector('.userSearchTable').style.opacity = "100"

            var username = result[i].username;

            table.style.border = "4px solid black"

            table.style.borderCollapse = "seperate"

            var row = table.insertRow(0);

            row.onclick = cellClicked("Test");

            var cell1 = row.insertCell(0);
            cell1.style.width = "80px"
            cell1.style.height = "50px"
            cell1.setAttribute("class", "UserImage")

            var image = document.createElement("img");
            image.height = "50"
            image.width = "50"
            image.style.backgroundColor = "green"
            image.style.margin = "15px 15px 15px 12px"
            image.style.padding = "0px 0px 0px 0px"
            image.style.borderRadius = "25px"
            image.style.borderColor = "black"
            image.style.border = "2px solid black"
            cell1.appendChild(image)

            var cell2 = row.insertCell(1);
            cell2.style.fontSize = "20"
            cell2.style.fontFamily = "Arial, Helvetica, sans-serif"
            cell2.style.fontWeight = "Semi Bold"
            cell2.innerHTML = username


        }

    error : function b(jqxhr, status, exception) {
            alert(status);
    }

    }
})

是否可以使一行可點擊,以便調用 onclick 函數? 我已經嘗試將.onclick添加到行中,但沒有奏效。 我還需要知道正在單擊哪一行,因為我需要該行的單元格的 innerHTML。

假設您的表是在頁面加載后寫入或創建的,您需要事件委托 document上設置單擊偵聽器,然后測試tagName以查看您是否在TD

 document.addEventListener('click', function(e) { if (e.target.tagName.toLowerCase() === "td") { let tr = e.target.closest('tr'); console.log('found td tag with this contents: ', e.target.innerHTML) console.log('found tr tag with this contents: ', tr.innerHTML) } else { console.log('not a table cell', e.target.tagName) } }) setTimeout(function() { document.querySelector('#content').innerHTML += "<table><tr><td>or me</td><td>or me too</td></tr></table>" }, 1000);
 <div id="content"> <div>try clicking me</div> </div>

暫無
暫無

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

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