javascript在拖动开始时获得父div

时间:2018-05-06 02:25:27

标签: javascript html drag-and-drop jquery-ui-draggable

我在拖动Urgent Doing时尝试获取文字div class="Card-Container"。我已经正确地获取了id(通过JS),但我不确定如何获取作为Card-Container父类的类的值。我试过this SO solution但是无法弄清楚如何正确绑定到drag_start函数。

要查看输出,请尝试拖动黑色标题框

    function drag_start(ev) {
        var cardid = ev.target.id;
        var classtext = $('#'+cardid).parents("div").prev().text();//$(cardid).parents("div").prev().text()
        ev.dataTransfer.setData("elem_id", cardid);
        ev.dataTransfer.setData("div_from_classname", classtext);//Lane-Title-2
        console.log("picked up card: " + cardid + " from div classname: " + classtext);
    }
    <html>
    <head></head>
    <body>
    
    <div class="Lane-Container-2">
      <div class="Lane-Title-2">Urgent Doing</div>
      <div class="Lane-Area-2">
                <div class="Card-Container" draggable="true" ondragstart="drag_start(event)" id="11111">
                <div class="Card-Title" style="background-color: black; border-color: black;" onclick="">xxx</div>
                <div class="Card-Body" style="background-color:@i.TypeColorHex; border-color: @i.TypeColorHex;">yyy</div>
            </div>
      </div>
    </div>  

    <div class="Lane-Container-2">
      <div class="Lane-Title-2">2.....Urgent Doing</div>
      <div class="Lane-Area-2">
                <div class="Card-Container" draggable="true" ondragstart="drag_start(event)" id="22222">
                <div class="Card-Title" style="background-color: black; border-color: black;" onclick="">xxx</div>
                <div class="Card-Body" style="background-color:@i.TypeColorHex; border-color: @i.TypeColorHex;">yyy</div>
            </div>
      </div>
    </div>  
    </body>

2 个答案:

答案 0 :(得分:0)

您可以使用$(".Card-Container").parents("div").prev().text()获取所需的div文本

console.log($(".Card-Container").parents("div").prev().text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="Lane-Container-2">
  <div class="Lane-Title-2">Urgent Doing</div>
  <div class="Lane-Area-2">
            <div class="Card-Container" draggable="true" ondragstart="drag_start(event)" id="@i.Id">
            <div class="Card-Title" style="background-color: black; border-color: black;" onclick="">xxx</div>
            <div class="Card-Body" style="background-color:@i.TypeColorHex; border-color: @i.TypeColorHex;">yyy</div>
        </div>
  </div>
</div>

答案 1 :(得分:0)

试试这样:

....
ev.dataTransfer.setData("div_from_classname", $(this).parent().className);
....