【问题标题】:jQuery UI get property of element in draggable div on drop:jQuery UI 在拖放时获取可拖动 div 中元素的属性:
【发布时间】:2011-06-23 22:40:22
【问题描述】:
$('#drop_area').droppable({
    accept: '.draggable',
    drop: on_element_drop
});

function on_element_drop(event, ui){

}

<div class="draggable">
    <img src="test.png" alt="3">
</div>

我试图弄清楚如何从传递给“on_element_drop”的“ui”参数中获取此可拖动 div 中图像的“alt”属性。有人知道怎么做吗?

我似乎得到的最接近的是:

ui.helper.context.children[0].attr('alt');

但是这不起作用。

【问题讨论】:

    标签: jquery jquery-ui jquery-selectors draggable jquery-callback


    【解决方案1】:
    ui.draggable.find("img").attr("alt")
    

    http://jsfiddle.net/3SfBJ/2

    【讨论】:

      【解决方案2】:

      您的可拖动 div 仅包含一个 img 元素。所以下面这个是对的

       ui.draggable.find("img").attr("alt")
                        OR
       ui.draggable.children("img").attr("alt")
      

      但是如果你的可拖动对象包含更多的 img 元素,如下所示

      <div class="draggable">
          <img src="test.png" alt="3">
          <img src="test.png" alt="4">
      </div>
      

      那么你不能使用上面的代码来查找第二个 img 元素的 alt 值。所以你可以试试这个:

      ui.draggable.find("img:last-child").attr("alt")
                         OR
      ui.draggable.children("img:last-child").attr("alt")
      

      这个例子展示了如何在父对象中找到实际对象的一般思路。 您可以使用类来区分您的子对象。这既简单又有趣。即

      <div class="draggable">
          <img class='first' src="test.png" alt="3">
          <img class='second' src="test.png" alt="4">
      </div>
      

      你可以这样做:

      ui.draggable.find(".first").attr("alt")
      

      具体如下:

      ui.draggable.find("img.first").attr("alt")
      

      您可以像上面的代码一样使用 find 或 children。如需更多信息,请访问儿童http://api.jquery.com/children/ 和查找http://api.jquery.com/find/

      【讨论】:

        【解决方案3】:

        我认为您发布的内容还有更多的 html 和 javascript?喜欢可放置的 div 吗?

        您应该能够将其添加到您的放置处理程序中

        ui.draggable.children(0).attr('alt')
        

        如果添加额外的 html,使用 find 也可以

        ui.draggable.find('img').attr('alt');
        

        祝你好运!

        【讨论】:

          猜你喜欢
          • 2017-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-07
          相关资源
          最近更新 更多