getElementById返回null?(Vue中)

3

我试图寻找答案,但没有成功。

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

它在jQuery中可以运行,但是在纯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 前

顺便问一下,我需要为 Bootstrap 使用 jQuery,如果我不使用它改变 DOM 的话,在 Vue 中也使用它会有问题吗?


3
请尝试使用 document.getElementById('sell'),不需要加上井号(#)。 - Stéphane Ammar
3个回答

4

将id参数中的#号删除,如下所示:

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

1
哦,谢谢!我的错!我忘记了如何使用原生JS。对不起! - Philipp Mochine

1

document.getElementById('#sell')不需要使用#来识别Id。这是你在jQuery选择器中使用的语法,但DOM选择器会直接取字符串并与ID属性值匹配。同样适用于document.getElementByClassName(),在此情况下,您无需使用.来识别类。

Mozilla MDN文档在这里给出了一个示例。

这应该可以工作:

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

-4

请尝试使用

$(document).ready(function(){ console.log($("#sell")); });

1
OP已经声明“它可以使用jQuery”,那么这个答案怎么会有帮助呢? - Jeff
我相信原帖作者在这条评论之后添加了那个内容。虽然这个回答不太清楚,但是这条评论是不必要的。 - Andrew Craswell
无论如何感谢您!@Jaswinder - Philipp Mochine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接