在下面的代码片段中,我们按类名 abc 分列0个元素:
var tbody = document.getElementsByClassName('abc');
console.log('tbody: ' + tbody.length)
var unKnown = document.getElementsByClassName('edf');
console.log('unKnown: ' + unKnown.length)
<tbody class="abc">
<tr><td>Hi!</td></tr>
</tbody>
<dflgkjldk class="edf" />
但javasctip找到了未知元素。你知道原因吗?
答案 0 :(得分:1)
我可能错了,但我认为如果你使用不正确的元素(读取知道元素错误你的tbody的例子),浏览器足够聪明,可以从DOM中过滤掉它。
包含未知元素,因为在HTML中您可以指定自己的元素。并且浏览器默认不知道如何处理它们,但它知道它应该包含在DOM中。
阅读关于unknow元素的内容以及它们为何有用:Is it OK to use unknown HTML tags?
答案 1 :(得分:1)
缺少“Table”元素会导致已知的“tbody”标记不正确,因此会忽略它。如果你只是用“table”标签包裹你的tbody,那就可以了。
// translate coords in viewport to internal coords of canvas
const translateCoords = ({clientX, clientY}) => {
// dimensions of canvas element (top-left with respect to border-box)
const bcr = canvas.getBoundingClientRect();
// offsets from border and padding
const sideWidth = ["top", "right", "bottom", "left"].reduce((sum, side) => {
sum[side] = Object.values($(canvas).css([
`border-${side}-width`,
`padding-${side}`
])).reduce((a, b) => a + parseFloat(b), 0);
return sum;
}, {});
// ratio of internal canvas resolution to canvas displayed dimensions
const scaleX = canvas.width / (bcr.width - (sideWidth.left + sideWidth.right));
const scaleY = canvas.height / (bcr.height - (sideWidth.top + sideWidth.bottom));
// translate and scale screen coords to canvas internal coords
const x = (clientX - (bcr.left + sideWidth.left)) * scaleX;
const y = (clientY - (bcr.top + sideWidth.top)) * scaleY;
return {x, y};
};
// example event listener
canvas.addEventListener("click", (event) => {
const {x, y} = translateCoords(event);
// do something with translated coordinates
console.log(x, y);
});
var tbody = document.getElementsByClassName('abc');
console.log('tbody: ' + tbody.length)
var unKnown = document.getElementsByClassName('edf');
console.log('unKnown: ' + unKnown.length)