简体   繁体   English

如何使用 JavaScript 添加类的元素

[英]How I can add element's of class using JavaScript

How I can add the element's of class using JavaScript如何使用 JavaScript 添加类的元素

<div class="col-md-4 col-xs-6 work-item web-design" id=SetCategory">
.
.
<script>
        document.getElementById("SetCategory").classList.add({{ $category->name }}' ');
</script>
.
.
</div> <!-- end work-item -->

In my display the <script> do not work.在我的显示中<script>不起作用。

PS $category->name is food , shop , travel , hotel , route since the name of category that cause different display when I click button PS $category->namefood , shop , travel , hotel , route因为当我点击按钮时导致不同显示的类别名称

This seems like college/university assignment and is not the purpose of stack overflow we not here to help anyone cheat as you should be aware of taking help from this website requires Citation.这看起来像是大学/大学作业,并不是堆栈溢出的目的,我们不是来帮助任何人作弊的,因为您应该知道从本网站获取帮助需要引用。

your problem is this,你的问题是这样的

document.getElementById("SetCategory").classList.add({{ $category->name }}' ')

It's not valid Javascript it's not even valid C Syntax.它不是有效的 Javascript,甚至不是有效的 C 语法。

1) Please learn how to use the web browsers inspector (Console Tab) using chrome, firefox, Edge & IE 11 press F12, as it would show you an error along the lines of Uncaught SyntaxError: Unexpected token { in the console output. 1) 请了解如何使用 chrome、firefox、Edge 和 IE 11 的 Web 浏览器检查器(控制台选项卡)按 F12,因为它会在控制台输出中显示类似Uncaught SyntaxError: Unexpected token {的错误。

2) Javascript in browsers has an amazing documentation resource called, MDN checkout: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList particularly line 9 of the first code example on the page, that code example for posterities sake is: 2) 浏览器中的 Javascript 有一个很棒的文档资源,称为 MDN checkout: https : //developer.mozilla.org/en-US/docs/Web/API/Element/classList特别是页面上第一个代码示例的第 9 行,为后人着想的代码示例是:

const div = document.createElement('div');
div.className = 'foo';

// our starting state: <div class="foo"></div>
console.log(div.outerHTML);

// use the classList API to remove and add classes
div.classList.remove("foo");
div.classList.add("anotherclass");

// <div class="anotherclass"></div>
console.log(div.outerHTML);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM