【发布时间】:2017-09-30 15:13:50
【问题描述】:
- 我是 js 新手。
- 你能告诉我为什么我得到了 sports-title 和third 的空值吗?
- 因为我们有一个包含内容的 div。 运动标题---->{“0”:{}} 第三---->{}
- 在下面提供我的代码。
findStringInsideDiv() {
/*
var str = document.getElementsByClassName("sports-title").innerHTML;
*/
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}
【问题讨论】:
-
仅引用对象是不够的,您必须从该对象获取文本
-
@Grisza 你好,你能告诉我为什么我在输出中看到 0 ---> {"0":{}}
-
您希望在
sportsTitle和third中看到什么? -
0来的原因是什么??
-
因为使用 getElementsByClassName 你得到数组,因此得到“0”,当我在没有 JSON.stringify 的情况下输入时,我得到了
sports-title---->[object HTMLCollection]
标签: javascript jquery html css reactjs