简体   繁体   中英

My function doesn't work twice in JavaScript

I have a table with numerous rows and columns and want to change the placeholder text, 'Cell 1' and 'Cell 2' (in column 1 and 2), within the td cells to 'Success'.

I have written a function to do this, but it only changes the first cell when I click it and no others when I try to click them.

document.querySelector('td').addEventListener('click', button8Click);

function button8Click() {
    document.querySelector('td').innerHTML = "Success";
}

I need to specifically target the td element, and thought I did so but I am at a standstill.

I guess you don't know how the querySelector works. It selects the first td element. This is why it only works once.

You need something like this:

function changeContent(i) {
    document.querySelectorAll('td')[i].innerHTML = "Success";
}

This will change the td element with the number i.

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document. If you need to add function to all the td elements try

 Array.from(document.getElementsByTagName('td')).forEach(it => {it.addEventListener('click', button8Click)})

Also you need to change you function to identify which row is clicked and should be changed.

function button8Click(event) {
    event.target.innerHTML = "Success";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM