前端页面:一直报Cannot set property 'height' of undefined

深藏阁楼爱情的钟 2022-03-07 01:18 267阅读 0赞

1、出现错误的例子,只拷贝了项目中关键出现问题的部分

例子中明明写了style=’height:16px’这个属性,但是为什么还说height未定义呢

通过打印发现:cks.each(function () {
autoTextAreaHeight($(this));
});中的$(this)取出来被当成数组处理了,所以要加上[0]

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
  6. <title>菜鸟教程(runoob.com)</title>
  7. <script>
  8. var element = "<span>" +
  9. "<input type='checkbox' value='" + 0 + "'>" +
  10. "<textarea style='height:16px; width:100px;margin-left:7px;' class='show_text' oninput='autoTextAreaHeight(this)' "+
  11. ">asdsaaaaaaaaaaaaawqdqwwqa</textarea>"
  12. //$.find("body").append(element);
  13. $(window).load(function(){
  14. //用jq在body中动态添加元素
  15. $(document.body).append(element);
  16. $(document.body).append(element);
  17. //初始化调用文本域高度自适应方法
  18. $(function () {
  19. var cks = $(".show_text");
  20. cks.each(function () {
  21. autoTextAreaHeight($(this));
  22. })
  23. })
  24. });
  25. //文本域自适应
  26. function autoTextAreaHeight(o) {
  27. o.style.height = o.scrollTop + o.scrollHeight + "px";
  28. }
  29. </script>
  30. </head>
  31. <body>
  32. </body>
  33. </html>
  34. 修改成

cks.each(function () {

  1. autoTextAreaHeight($(this)[0]);

})

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读