【问题标题】:My javascript is not working for dom traversing我的 javascript 不适用于 dom 遍历
【发布时间】:2018-01-27 11:12:16
【问题描述】:

我正在学习 Javascript 和 jQuery。我最近发现了 DOM Traversing,但是当我为它编写代码时,它只是没有响应。 代码是:

<!DOCTYPE html>
<head>
<title>Test</title>

</head>
<body>
<script>

$('div').onclick = function pi() {
var p = document.getElementsByClassName('.p');

p.value("hello guys");
};

</script>
<div style="background-color:blue; height:1000px; width:100%px;">
</div>
<div style="height: 600px; background-color: aqua;width: auto;">
<p style="color:black; font-size: 40px;" class="p">d
</p>
</div>
</body>
</html>

【问题讨论】:

  • 去掉点,document.getElementsByClassName('.p')应该是document.getElementsByClassName('p')
  • 那里...错了很多...
  • 错的太他妈高了,我连表情包都没有。
  • 开始 html 标记在哪里?哈哈,它一直在交付。
  • 也许这实际上是一个我们能发现多少错误的问题......

标签: javascript jquery dom sass jquery-events


【解决方案1】:

让我们来解决问题:

1) 你没有在任何地方包含 jQuery,所以你不能使用它。如果你想使用它,你需要添加一个脚本标签(在你当前使用的&lt;head&gt;标签之间)链接到它——比如:

<script
  src="https://code.jquery.com/jquery-2.2.4.js"
  integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
  crossorigin="anonymous"></script>

2) 这就是 jQuery 的 onclick(实际上是 click)的工作原理。 click 是一个接受函数的 function。您传递给click 的函数在用户单击目标时执行。您的代码将覆盖 jQuery 的 click,它应该是:

$('div').click(function pi() {
  // code
})

3) 这不是被禁止的,但由于您已经在使用 jQuery,因此回退到像 getElementsByClassName 这样的原生 DOM 获取 API 并没有多大意义。我建议你改用$('.p'):

$('div').click(function pi() {
  // it's good to prefix jquery collection variables with a $
  // makes it obvious what is in them
  var $p = $('.p')
})

旁注你可以只使用$('p')并根据标签名进行查询,这样可以避免分配多余的类名

4) .value() 既不是 jQuery 方法也不是本机方法。 jQuery 有一个val() 方法,但这是用于设置selectinput 等输入元素的value 属性。您可能想要做的是更改p 的文本标签。使用 jQuery 将是 $('p').text('new text')。请注意,调用这将更改 ALL p 元素或 class="p" 元素的文本:

$('div').click(function pi() {
   var $p = $('.p')
   $p.text('hello guys')
});

希望这对您有所帮助

【讨论】:

  • @BenFortune 感谢您指出这一点,不知道我是怎么错过的!更新
【解决方案2】:

我在这里发现了三个错误。

  1. 看起来您正在使用 jQuery,所以在 Script 标签中插入 jQuery 文件。
  2. 按类名调用时不应使用“.p”。
  3. 一些语法错误

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('div').click(function(){

var p = document.getElementsByClassName('p'); //returns an Array with the class name "p"
p[0].innerHTML = "Hello Guys"; // first element of all element in "p" array

//or you could use the jquery way mentioned down below

// $('.p').html("Hello Guys"); 
 
});
});
</script>

</head>
<body>
  <div style="background-color:blue; height:100px; width:100%px;">
  </div>
  <div style="height: 100px; background-color: aqua;width: auto;">
    <p style="color:black; font-size: 40px;" class="p">d</p>
  </div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多