简体   繁体   English

HTML元素的值未定义但已设置

[英]value of HTML element is undefined but it is set

I want to set checkbox after the page has renderet to the matching state of the backend. 我想在页面渲染到后端的匹配状态后设置复选框。

I implemented this function for that purpose what does the job so far 为此目的,我实现了这个功能到目前为止的工作是什么

Updated to user-suggestion It doesn't matter if cbs[i].dataset.thvalue or cbs[i].dataset.value 更新为user-suggestion cbs [i] .dataset.thvalue或cbs [i] .dataset.value无关紧要

 function updateCheckboxes () {

  let activeCheckbox = '<input type="checkbox" onclick="handleClickOnReduce()" checked>'
  let inactiveCheckbox = '<input type="checkbox" onclick="handleClickOnReduce()">'

  let cbs = document.getElementsByTagName('td')
  for (let i = 0; i < cbs.length; i++) {
    if (cbs[i].id === 'reduceCheckbox' || cbs[i].id === 'slCheckbox') {
      if (cbs[i].dataset.thvalue === 'true') {
        cbs[i].innerHTML = activeCheckbox
      }
      else {
        cbs[i].innerHTML = inactiveCheckbox
      }
    }
  }
}

HTML part, using Thymeleaf HTML部分,使用Thymeleaf

    <td id="reduceCheckbox" data-th-value="${car.isReduced()}"></td>
    <td id="slCheckbox" data-th-value="${car.isSl()}"></td>

But the browser claims by printing out the value, that it is undefined, even if the value is set as you can see in the picture live from the browser. 但浏览器通过打印输出值来声明它是未定义的,即使设置的值正如您在浏览器中的实时图片中所看到的那样。

在此输入图像描述

Due to the docu my syntax should be correct? 由于文档我的语法应该是正确的?

https://www.w3schools.com/jsref/prop_option_value.asp https://www.w3schools.com/jsref/prop_option_value.asp

Any suggestion? 有什么建议吗?

Ty

You HTML is invalid. 您的HTML无效。

<td> elements do not have value attributes. <td>元素没有value属性。 (The link you reference is talking about <option> , not <td> ). (您引用的链接是<option> ,而不是<td> )。

Your browser is not mapping the JS value property onto your invented attribute. 您的浏览器未将JS value属性映射到您的发明属性。

If you want to add arbitrary data to an element, use a data-* attribute and read it using the dataset API . 如果要向元素添加任意数据,请使用data-*属性并使用数据集API读取它。

It looks like my misunderstanding of the Thymeleaf syntax with regards to th-data led to that issue. 看起来我对Thymeleaf语法的误解导致了这个问题。

This is the fix: 这是修复:

<td id="reduceCheckbox" th:attr="data-value=${car.isReduced()}"></td>

Access via 访问通过

 console.log(cbs[i].dataset.value)

value is not valid attributes in td tag. value不是td标记中的有效属性。 you can use abbr attributes 你可以使用abbr属性

<td id="reduceCheckbox" abbr="true"> <input type="checkbox" onclick="handleClickOnReduce()"> </td>

then you can get it 然后你就可以得到它

console.log(cbs[i].abbr)

Note: The abbr attribute is not supported in HTML5. 注意:HTML5不支持abbr属性。

For HTML5 you can use headers attributes 对于HTML5,您可以使用标头属性

<td id="reduceCheckbox" headers="true">
    <input type="checkbox" onclick="handleClickOnReduce()">
</td>

then you can get it 然后你就可以得到它

console.log(cbs[i].headers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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