javascript 如何从div调用javaScript函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16480137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:52:21  来源:igfitidea点击:

how to call javaScript function from div

htmljavascript

提问by Sylvie Shamir

hello does anybody know how to call a JavaScript function from a div? my div and function look like this:

你好有人知道如何从 div 调用 JavaScript 函数吗?我的 div 和函数如下所示:

@foreach(var c in Model.matrix.Cells)
{
    <tr>
     <td class="tdHouse" >
        <div onload="styleCell(event)" class="cell" id="styleCell" ondrop="drop(event,@c.row,@c.column)" ondragover="allowDrop(event)" alt="one">                                                                
        </div>   
            <label hidden id="@c.room.Id" class="existRoomStyle" ondragstart="drag(event)" onmouseup="dragMouseUp(event)" title="@c.room.roomName"  style= "background-color:@c.room.color"> @c.room.roomName</label>                                  
            <img  hidden id="@c.socket.Id" alt="existSocket" class="existSocketStyle" src="~/Images/socket.jpg"  draggable="true" ondragstart="drag(event)" onmouseup="dragMouseUp(event)" title="socket" alt="one"/>                                       
            <img  hidden id="@c.socket.machine.Id"class="existMachineStyle" src="~/Images/MachineImages/@c.socket.machine.Image" draggable="true" ondragstart="drag(event)" title="machine" alt="one"/>                                      

     </td>
   </tr>                        
  }

<script>
function styleCell(ev) {
    ev.target.children[0].appendChild(document.getElementById("existRoomStyle"));
    ev.target.children[0].appendChild(document.getElementById("existSocketStyle"));
    ev.target.children[0].appendChild(document.getElementById("existMachineStyle"));
 }
</script>

回答by ApriOri

You can't call onload this way. w3schools list where no-load is applicableYou must separate the function call from the div.

您不能以这种方式调用 onload。 w3schools list where no-load is适用您必须将函数调用与 div 分开。

See this answer How to add onload event to a div element?

请参阅此答案 如何将 onload 事件添加到 div 元素?