javascript - 给 div 标签设置一个属性

标签 javascript jquery

我有一个简单的代码

<div class="content"></div>

我想用 javascript 来回显 div 标签内的内容以这种方式显示

<div class="content" something></div>

我需要它使用 javascript,因为如果屏幕宽度超过 960px,我想使用一个函数来回显某些东西 我在第二部分使用了这个答案 Do something if screen width is less than 960 px

提前谢谢你。

最佳答案

那个叫做attribute,设置属性你可以使用下面的方法。

纯 JS setAttribute() 方法:

element.setAttribute('name','value');

jQuery attr() 方法:

$(element).attr('name','value');

示例:

document.querySelector('.content').setAttribute('something',''); //Pure JS
//Or
$('.content').attr('something',''); //jQuery

希望这对您有所帮助。

关于javascript - 给 div 标签设置一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220068/

相关文章:

javascript - 允许模块与 AMD/CommonJs 或脚本标签一起工作的包装器?

javascript - 自动化测试 Android 应用程序?

php - jquery对文本进行颜色编码

javascript - 以选择器 ^= 开头的 css 在使用 javascript 更改类后不起作用

php - 关于 php 和 ajax-jquery 的问题

php - 带有 JSON 和 PHP 的动态行不会输出数据

javascript - jQuery、Asp.net -jAutoCalc : Implement auto calculation on the form to be appended in the table using jQuery

javascript - 创建多页PDF文档jsPDF

javascript - 打开模式时出现奇怪的空白

javascript - 关闭浏览器前显示的自定义弹出窗口