#javascript #html
#javascript #HTML
Вопрос:
Я использую JavaScript для динамического создания таблицы. Я хочу получить значение stationIdCell
, чтобы передать его refreshMETAR()
функции. Однако я не могу понять, как заставить это работать. Любая помощь будет оценена.
Вот моя таблица
const metarTableElement = document.querySelector('#metar_table')
const rowCount = metarTableElement.rows.length
if(rowCount > 6)
{
metarTableElement.deleteRow(rowCount - 1)
} else {
const row = metarTableElement.insertRow(1)
var stationIdCell = row.insertCell(0)
stationIdCell.innerHTML = `<button onclick="refreshMETAR(this.innerHTML)">${station_id}</button>`
//I want to pass this value to the function
var latitudeCell = row.insertCell(1)
latitudeCell.innerHTML = `${latitude}`
var longitudeCell = row.insertCell(2)
longitudeCell.innerHTML = `${longitude}`
var rawMETARCell = row.insertCell(3)
rawMETARCell.innerHTML = `${raw_metar}`
Вот функция, в которую я хочу передать значение ячейки:
const refreshMETAR = () => {
const stationElement = this.innerHTML //The value of the table cell should be read here
const station = stationElement.value
const alertPanelElement = document.querySelector('#alert_panel')
console.log(`entered: ${station}`)
validateADDSStation(station)
.then(response => response.json())
.then(json => {
let icao = null
let site = null
try{
icao = json.response.data[0].Station[0].station_id[0]
site = json.response.data[0].Station[0].site[0]
} catch(err) {
alertPanelElement.classList.remove('w3-hide')
alertPanelElement.classList.add('w3-show')
stationElement.focus()
stationElement.select()
console.log("BAD CODE")
}
console.log(`RETURN VALUE FROM VALIDATE: ${icao}`)
if( station !== icao){
console.log(`ICAO ${icao} not found`)
alertPanelElement.classList.remove('w3-hide')
alertPanelElement.classList.add('w3-show')
}
else {
alertPanelElement.classList.remove('w3-show')
alertPanelElement.classList.add('w3-hide')
fetch(`${ADDS_METAR_URL}${station}`)
.then(response => response.json())
.then(json => {
// printValues(json)
updateWeatherOutput(json, site)
})
}
})
}
Комментарии:
1. вы пробовали это «const refreshMETAR = (htmlContent) => {…}»
2. @Rumesh не могли бы вы подробнее рассказать о том, что вы говорите? Должен ли я сохранить
this.innerHTML
? Потому что я только что попробовал это, и он продолжает возвращатьсяUncaught TypeError: Cannot read property 'value' of undefined
Ответ №1:
Похоже, вы пытаетесь отправить параметры station_id в функцию refreshMETAR в качестве параметров для отправки запроса при нажатии кнопки. в вашем коде есть 2 проблемы.
<button onclick="refreshMETAR(this.innerHTML)">${station_id}</button>
я думаю, что это в приведенном выше заявлении будет ссылкой на window, а не на элемент button или элемент stationIdCell.const refreshMETAR = () => { const stationElement = this.innerHTML //The value of the table cell should be read here
вы отправляете (this.innerHTML) как в params , но это не способ использовать параметр in
пожалуйста, попробуйте это:
stationIdCell.innerHTML = `<button onclick="refreshMETAR('${stationId}')">${station_id}</button>`
const refreshMETAR = (stationId) => {
const station = stationId
console.log(`entered: ${station}`)
Ответ №2:
типичный случай делегирования событий
первая часть:
// GLOBAL
const metarTableElement = document.querySelector('#metar_table')
document.addEventListener('click', refreshMETAR )
//...
let rowCount = metarTableElement.rows.length
if (rowCount > 6)
{
metarTableElement.deleteRow( --rowCount )
}
else
{
let row = metarTableElement.insertRow()
row.insertCell().innerHTML = `<button class="cl_METAR">${station_id}</button>`
row.insertCell().textContent = latitude
row.insertCell().textContent = longitude
row.insertCell().textContent = raw_metar
//...
щелчки по кнопкам…
function refreshMETAR(evt)
{
if (!evt.target.matches('button.cl_METAR')) return // reject clicks from somewhere else
const station = evt.target.textContent // === value in ${station_id}
// ...
}