【问题标题】:Javascript .css not working nor jquery .blueJavascript .css 不工作也不 jquery .blue
【发布时间】:2018-04-24 23:04:42
【问题描述】:

我在设计简单的 html 时遇到了各种麻烦 在 js 和 jQuery 中 这里似乎使用了一个jsfiddle来说明。 我是新手,看不到控制台输出或所需结果 所以我问这个问题是为了更多地了解如何提供帮助; 我确实搜索过 .css 不工作和变体

javascript

.css() 是 jQuery。 .style 是 js。

document.getElementsByTagName('pre').text.css("color: blue;"); jQuery: const preSentences = $("pre").text().split(".") console.log({preSentences})

    //no err no workee in chrome

// preSentences.forEach(function(str) { $(this).css("color: blue; border: 1px solid black")}); // $.each(preSentences, function(str) { $(this).blue }) // preSentences[1].style("color: blue; border: 1px solid black");

我认为小提琴就在这里 - 我尝试了嵌入链接,但它没有显示: https://jsfiddle.net/Lz8nh50o/

【问题讨论】:

  • document.getElementsByTagName('pre').text.css("color: blue;") 甚至无法有效使用原生 DOM 方法。 - 你检查开发者工具控制台是否有错误?

标签: javascript jquery css text-styling


【解决方案1】:

getElementsByTagName 将返回一个标签数组,您必须遍历每个标签来设置样式。此外,您正在使用 .css() 但这是一个 jQuery 函数。你必须使用风格。

试试这个:

var preTags = document.getElementsByTagName('pre');
for(var i=0; i<preTags.length; i++){
  preTags[i].style.color='blue';
}

【讨论】:

  • 我看到这行得通。一个 jquery 等价物将帮助我理顺我的理解。
  • const jsts = document.getElementsByTagName('pre'); jsts.style.color='蓝色';
  • 'jsts' 是一个标签数组,您必须为每个标签单独设置样式。尝试使用 console.log(jsts) 而不是 console.log({jsts})
【解决方案2】:

你可以用 ES6 for-of 循​​环遍历 htmlCollention,看起来更干净。

let list = document.getElementsByTagName('pre')

for (let currentElement of list){
    currentElement.style.color ='blue';
}

jQuery 等价物是

jQuery('pre').css('color','blue');

【讨论】:

    【解决方案3】:
    // JS
    document.querySelectorAll('pre').forEach(str => {str.style.color='blue';})
    
    //jQuery
    jQuery('pre').css('color','blue');
    

    【讨论】:

    • document.querySelectorAll('pre').forEach(str => str.style.color='blue') 。在这种情况下,您甚至可以去掉弯括号和分号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多