如何从带有DOM的输入中选择parentNode的ID?

时间:2017-07-26 23:34:42

标签: javascript dom input

当我点击输入时,它应该给我div的ID,但是在控制台中给我一个错误"无法读取属性' id'未定义"。



function add(){
  console.log(this.parentNode.id);
}

<div id="example">
  <img src="" alt="" />
  <input type="button" value="click me" onclick="add()">
  <h3>Title</h3>
  <p>Price</p>
  <p>Description</p>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

add函数处定义参数,并将this传递给函数调用。不使用附加到元素.onclick的{​​{1}}或.addEventListener()是浏览器中JavaScript的事件属性处理程序中函数调用中的全局对象this

window
function add(el) {
  console.log(el.parentNode.id);
}

或者,使用<div id="example"> <img src="" alt="" /> <input type="button" value="click me" onclick="add(this)"> <h3>Title</h3> <p>Price</p> <p>Description</p> </div>

.addEventListener()
function add(event) {
  console.log(this.parentNode.id);
}

onload = function() {
  document.querySelector("#example input[value='click me']")
  .addEventListener("click", add)
}

答案 1 :(得分:0)

试试这个:

&#13;
&#13;
<div id="example">
  <img src="" alt="" />
  <input type="button" value="click me" onclick="add(this)">
  <h3>Title</h3>
  <p>Price</p>
  <p>Description</p>
</div>
&#13;
public void createGrid()
    {
        for (int i = 0; i < 8; i++)
        {
            grid[i] = new Cell[8];
            for (int j = 0; j < 8; j++)
            {
                chance = rand1.Next(0, 6);
                if (chance == 0 && bombAmount < 10)
                {
                    grid[i][j] = new Cell(true);
                    bombAmount++;
                }
                else
                {
                    grid[i][j] = new Cell();
                }

                grid[i][j].Name = "grid" + i.ToString() + j.ToString();
                grid[i][j].Location = new System.Drawing.Point(i * 49, j * 49);
                grid[i][j].Size = new System.Drawing.Size(50, 50);
                grid[i][j].TabIndex = 0;
                grid[i][j].Font = new System.Drawing.Font("Microsoft Sans Serif", 26.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

            }
        }

        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j <8; j++)
            {
                this.Controls.Add(grid[i][j]);
            }
        }
    }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

的onclick = “添加(这)”

功能添加(ele)

将元素传递给我的朋友

相关问题