将JavaScript的数据形式发送到Servlet:获取按钮旁边的嵌套元素的相关数据

问题描述 投票:0回答:1

我有一个带有视频div和按钮的简单html:

<div class = "video-row">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/QmHCn5xXHjI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    <div class="add-button green-button light-button">Add video</div>


</div>

我想在单击按钮时将视频的src数据发送到Java servlet:

$(document).on("click", ".add-button", function () {  
           sendData();
});
var sendData = function()  {
    $.ajax({
        url: "addcomedian",
        type: "post", //send it through get method
        data: {
            number: 4,
            sender: "add-button",
            url: url,
        },
     success:
        ...
}

如何获取视频的网址,即src标签的值?页面上会有很多这样的视频,每个视频都有一个添加按钮。

javascript java servlets
1个回答
1
投票

找到被单击元素的父级,然后找到iframe子级:

$(document).on("click", ".add-button", function (event) {  
  var button = $(event.target); // Find the button that was clicked
  // Find the video element, first finding the parent
  var videoElement = button.parents(".video-row").find("iframe");
  console.log(videoElement.attr("src")); // get the 'src' attribute
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "video-row">
  <iframe width="160" height="90" src="https://www.youtube.com/embed/QmHCn5xXHjI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  <div class="add-button green-button light-button">Add video</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.