为了账号安全,请及时绑定邮箱和手机立即绑定

jquery在我试图抓取的div元素的id上得到一个“未定义”

jquery在我试图抓取的div元素的id上得到一个“未定义”

慕田峪7331174 2021-12-23 14:28:59
所以我使用 JavaScript 动态生成 HTML 代码,这些代码加载到我的 Firebase 实时数据库中的所有图像中。我目前正在实现一个附加到每个图像的按钮,单击该按钮将删除该图像。但是,在使用标准 JavaScript 和 Jquery 多次尝试获取此 div 的 ID 属性后,警报框中的 id 始终为“未定义”。检查网页让我看到图像的 id 总是加载得很好,所以我知道它在那里。JavaScript 函数来响应我的 html 'onclick 事件'function deleteFile(){var postId = $(this).closest('div').attr('id');alert("You have selected id: " + postId);var sure = confirm("Are you sure you want to delete this post?"); if(sure){    firebase.database().ref().child('Posts/' + postId).remove().then(function(){        alert("Post deleted sucessfully");      });    }  };附加的图像是在实际的 chrome 检查器上生成的 html。ID当然都是唯一的。
查看完整描述

2 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

this在您的 html onclick 属性上添加参数,使其成为deleteFile(this)


然后在你的 js 上


function deleteFile(element){

    var postId = $(element).closest('div').attr('id');

    alert("You have selected id: " + postId);

    var sure = confirm("Are you sure you want to delete this post?");

    if(sure){

        firebase.database().ref().child('Posts/' + postId).remove().then(function(){

            alert("Post deleted sucessfully");

        });

    }

};


查看完整回答
反对 回复 2021-12-23
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

与 onclick 配对$(this)不会像您预期的那样工作,因为$(this)有不同的上下文,您可以使用查看其值console.log($(this));

应该做的是向该按钮添加一个类并通过 jquery 绑定一个 onclick 事件。运行下面的代码片段。

  • 红色 div 包含通过 jquery 附加的 onclick 事件。

  • 黄色 div 包含附加到按钮属性 onclick 的 onclick 事件。

$(document).ready(function(){

   $(".getIdButton").click(function() {

      alert($(this).closest("div").attr("id"));

   });

});


function getId() {

  alert($(this).closest("div").attr("id"));

  console.log($(this));

}

div {

  width: 100px;

  height: 100px;

  padding: 20px;

  display: inline-block;

}


#red {

  background-color: red;

}


#yellow {

  background-color: yellow;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="red">

  <a href="#">Just a link</a>

  <button class="getIdButton">Click Me</button>

</div>


<div id="yellow">

  <a href="#">Just a link</a>

  <button onclick="getId()">Click Me</button>

</div>


查看完整回答
反对 回复 2021-12-23
  • 2 回答
  • 0 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号