getElementById返回null? (与Vue)

问题描述 投票:2回答:3

所以我试图找到答案,但没有成功。

window.onload = function() {
   console.log(document.getElementById('#sell'));
   if(document.getElementById('#sell')){
      alert('jo');
      //Init for Vue
   }
}

它适用于jQuery但不适用于vanilla JS为什么?

console.log(document.getElementById('#sell')); 

结果返回NULL

jQuery示例:

if ( $( "#sell" ).length ) {
   const app = new Vue({
          el: '#sell',
          components: { sellPicture }
   });
}

在我的sell.blade.php中看起来就是这样

... 
<div id="sell">
    <sell-picture></sell-picture>
</div>
....

我的脚本在/ body之前添加

只是一个附带问题。我需要jQuery for Bootstrap,如果我不用它改变DOM,在Vue中使用它也不好吗?

javascript jquery
3个回答
3
投票

从id param中删除#,如下所示

window.onload = function() {
   console.log(document.getElementById('sell'));
   if(document.getElementById('sell')){
      alert('jo');
      //Init for Vue
   }
}

1
投票

document.getElementById('#sell')不需要#来识别ID。这是您将在jQuery选择器中使用的语法,但DOM选择器将字面上取字符串并将其与ID属性值匹配。 document.getElementByClassName()也是如此,你不需要.来识别这个类。

Mozilla MDN文档提供了这个here的示例。

这应该工作:

window.onload = function() {
   console.log(document.getElementById('sell'));
   if(document.getElementById('sell')){
      alert('jo');
      //Init for Vue
   }
}

-1
投票

请尝试使用

$(document).ready(function(){ console.log($("#sell")); });
© www.soinside.com 2019 - 2024. All rights reserved.