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

所以我使用 JavaScript 动态生成 HTML 代码,这些代码加载到我的 Firebase 实时数据库中的所有图像中。我目前正在实现一个附加到每个图像的按钮,单击该按钮将删除该图像。但是,在使用标准 JavaScript 和 Jquery 多次尝试获取此 div 的 ID 属性后,警报框中的 id 始终为“未定义”。检查网页让我看到图像的 id 总是加载得很好,所以我知道它在那里。

http://img4.mukewang.com/61c4175100017d6909960200.jpg

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当然都是唯一的。


慕田峪7331174
浏览 193回答 2
2回答

白猪掌柜的

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");        });    }};

繁星淼淼

与 onclick 配对$(this)不会像您预期的那样工作,因为$(this)有不同的上下文,您可以使用查看其值console.log($(this));应该做的是向该按钮添加一个类并通过 jquery 绑定一个 onclick 事件。运行下面的代码片段。红色 div 包含通过 jquery 附加的 onclick 事件。黄色 div 包含附加到按钮属性 onclick 的 onclick 事件。$(document).ready(function(){&nbsp; &nbsp;$(".getIdButton").click(function() {&nbsp; &nbsp; &nbsp; alert($(this).closest("div").attr("id"));&nbsp; &nbsp;});});function getId() {&nbsp; alert($(this).closest("div").attr("id"));&nbsp; console.log($(this));}div {&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; padding: 20px;&nbsp; display: inline-block;}#red {&nbsp; background-color: red;}#yellow {&nbsp; background-color: yellow;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="red">&nbsp; <a href="#">Just a link</a>&nbsp; <button class="getIdButton">Click Me</button></div><div id="yellow">&nbsp; <a href="#">Just a link</a>&nbsp; <button onclick="getId()">Click Me</button></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript