- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个用有效 html 编写的属性字符串,我想将这些属性放在实际的 html 元素 上(而不是元素的 html string)。
例如,我在合理命名的 attributesStr
变量中有属性字符串,我想将这些属性添加到 #htmlElement
div。
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
The HTML element!
</div>
运行 JQuery/JavaScript 代码后,#htmlElement
应如下所示:
<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue>
The HTML element!
</div>
如何在 JavaScript 或 Jquery 中执行此操作?
第一次尝试:我想我可以通过 .split()
ing attributesStr
空格来做到这一点,然后在 上拆分每个单独的属性键值对>=
,然后迭代该数组并使用 JQuery 的 .prop()
或 .attr()
添加每个键值对,但这行不通有两个原因:
style
和 title
属性上失败,因为它们有空格。最佳答案
获取 attributesStr
并将其插入到现有的 outerHTML
中。为此,您需要通过删除现有标记、注入(inject)字符串并放回其余 html 来重建节点。
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
var element = document.getElementById('htmlElement');
var tag = element.tagName;
element.outerHTML = '<' + tag + attributesStr + element.outerHTML.substring(tag.length + 1);
<div id="htmlElement">
The HTML element!
</div>
关于javascript - 给一个html元素添加一串html属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565733/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!