【问题标题】:Need a conversion from Jquery to vanilla javascript需要从 Jquery 到 vanilla javascript 的转换
【发布时间】:2022-12-07 11:12:26
【问题描述】:

将其从 JQuery 转换为 javascript 时遇到问题。我试过 document.getElementbyClassName("tile").style.left = x * tileWidth + tileDepth * z + tileOffsetLeft + "px"。但它不喜欢那样并给我错误无法设置未定义的属性(设置“左”)。

export function createTiles() {
    for (let counter = 0; counter < coordinates.length; counter++) {
        const coord = coordinates[counter];
        const [x,y,z] = coord;
        const image = images[counter];

        const tile = $("<div></div>")
            .addClass("tile")
            .css({
                left: x * tileWidth + tileDepth * z + tileOffsetLeft + "px",
                top: y * tileHeight + tileDepth * z + tileOffsetTop + "px",
                zIndex: z
            });
        const tileFront = $("<div></div>")
            .addClass("tileFront")
            .css({
                width: tileWidth + "px",
                height: tileHeight + "px",
                borderRadius: tileRoundness + "px"
            })
            .append(image);
        tile.append(tileFront).appendTo("#game");        
    }
} 

【问题讨论】:

  • 它不喜欢它,因为它应该是getElementsbyClassNamegetElementsbyClassName 返回一个您不能直接应用样式的节点列表——您需要遍历节点列表并将样式应用到每个节点。

标签: javascript jquery


【解决方案1】:

.addClass("tileFront") 更改为 .classList.add("tileFront") 试试看

【讨论】:

  • 这只回答了部分问题。
【解决方案2】:

也许这样的事情可以工作。

export function createTiles() {
  for (let counter = 0; counter < coordinates.length; counter++) {
    const coord = coordinates[counter];
    const [x, y, z] = coord;
    const image = images[counter];

    const tile = document.createElement("div");
    tile.classList.add("tile");
    tile.style.left = x * tileWidth + tileDepth * z + tileOffsetLeft + "px";
    tile.style.top = y * tileHeight + tileDepth * z + tileOffsetTop + "px";
    tile.style.zIndex = z;

    const tileFront = document.createElement("div");
    tileFront.classList.add("tileFront");
    tileFront.style.width = tileWidth + "px";
    tileFront.style.height = tileHeight + "px";
    tileFront.style.borderRadius = tileRoundness + "px";
    tileFront.append(image);

    tile.append(tileFront);
    document.getElementById("game").append(tile);
  }
}

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2016-03-09
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多