我可以向 HTML 标记添加自定义属性吗?

发布于 2024-08-11 07:58:44 字数 89 浏览 4 评论 0原文

我可以向 HTML 标记添加自定义属性吗?如下所示?

<tag myAttri="myVal" />

Can I add a custom attribute to an HTML tag like the following?

<tag myAttri="myVal" />

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

少女情怀诗 2024-08-18 07:58:44

您可以随意向元素添加自定义属性。但这将使您的文件无效。

在 HTML 5 中,您将有机会使用 data- 为前缀的自定义数据属性。

You can add custom attributes to your elements at will. But that will make your document invalid.

In HTML 5 you will have the opportunity to use custom data attributes prefixed with data-.

三人与歌 2024-08-18 07:58:44

您可以修改 !DOCTYPE 声明(即 DTD)以允许它,以便 [XML] 文档仍然有效:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

#IMPLIED 表示它是可选属性,或者您可以使用 #REQUIRED 等。

更多信息请参见DTD - 属性

You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

#IMPLIED means it is an optional attribute, or you could use #REQUIRED, etc.

More information is in DTD - Attributes.

岁月蹉跎了容颜 2024-08-18 07:58:44

不,这会破坏验证。

在 HTML 5 中,您可以/将能够添加自定义属性。像这样的东西:

<tag data-myAttri="myVal" />

No, this will break validation.

In HTML 5 you can/will be able to add custom attributes. Something like this:

<tag data-myAttri="myVal" />
北座城市 2024-08-18 07:58:44

jQuery data() 函数允许您将任意数据与 DOM 元素关联起来。 这是一个示例

The jQuery data() function allows you to associate arbitrary data with DOM elements. Here's an example.

小草泠泠 2024-08-18 07:58:44

在 HTML5 中:是:使用 data- 属性

 <ul>
  <li data-animal-type="bird">Owl</li>
  <li data-animal-type="fish">Salmon</li>
  <li data-animal-type="spider">Tarantula</li>
</ul> 

In HTML5: yes: use the data- attribute.

 <ul>
  <li data-animal-type="bird">Owl</li>
  <li data-animal-type="fish">Salmon</li>
  <li data-animal-type="spider">Tarantula</li>
</ul> 
静若繁花 2024-08-18 07:58:44

是的,你可以做到!

有了下一个 HTML 标签:

<tag key="value"/>

我们可以使用 JavaScript 访问它们的属性:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter

Element.setAttribute() 如果属性不存在,则将属性放入 HTML 标签中。因此,如果您要使用 JavaScript 设置它,则无需在 HTML 代码中声明它。

key:可以是您想要的属性名称,但当前标签尚未使用。
value:它始终是包含您需要的字符串。

Yes, you can do it!

Having the next HTML tag:

<tag key="value"/>

We can access their attributes with JavaScript:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter

Element.setAttribute() put the attribute in the HTML tag if not exist. So, you don't need to declare it in the HTML code if you are going to set it with JavaScript.

key: could be any name you desire for the attribute, while is not already used for the current tag.
value: it's always a string containing what you need.

姐不稀罕 2024-08-18 07:58:44
var demo = document.getElementById("demo")
console.log(demo.dataset.myvar)
// or
alert(demo.dataset.myvar)
//this will show in console the value of myvar
<div id="demo" data-myvar="foo">anything</div>

var demo = document.getElementById("demo")
console.log(demo.dataset.myvar)
// or
alert(demo.dataset.myvar)
//this will show in console the value of myvar
<div id="demo" data-myvar="foo">anything</div>

伤痕我心 2024-08-18 07:58:44

是的,您可以,您在问题本身中做到了:

Yes, you can, you did it in the question itself: <html myAttri="myVal"/>.

清风挽心 2024-08-18 07:58:44

您可以通过 JavaScript 设置属性。

document.getElementById("foo").myAttri = "myVal"

You can set properties from JavaScript.

document.getElementById("foo").myAttri = "myVal"
身边 2024-08-18 07:58:44

使用 data-any ,我经常使用它们

<aside data-area="asidetop" data-type="responsive" class="top">

use data-any , I use them a lot

<aside data-area="asidetop" data-type="responsive" class="top">
不一样的天空 2024-08-18 07:58:44

使用自定义元素< /a>,通常添加不带 data- 前缀的自定义属性

以下是 HTML 标准:自定义元素 中的示例(请注意 country 属性):

<flag-icon country="nl"></flag-icon>

来自 MDN Web 文档:使用自定义元素(请注意 lc 属性):

<custom-square l="100" c="red"></custom-square>

With custom elements, it is common to add custom attributes without data- prefix.

Here is an example from HTML standard: Custom elements (note the country attribute):

<flag-icon country="nl"></flag-icon>

Another example from MDN Web Docs: Using custom elements (note the l and c attributes):

<custom-square l="100" c="red"></custom-square>
眼波传意 2024-08-18 07:58:44

示例如下:

document.getElementsByTagName("html").foo="bar"

这是另一个如何将自定义属性设置到 body 标签元素中的示例:

document.getElementsByTagName('body')[0].dataset.attr1 = "foo";
document.getElementsByTagName('body')[0].dataset.attr2 = "bar";

然后通过以下方式读取属性:

attr1 = document.getElementsByTagName('body')[0].dataset.attr1
attr2 = document.getElementsByTagName('body')[0].dataset.attr2

您可以在 DevTools 的 Console 中测试上述代码,例如

JS 控制台、Chrome 中的开发工具< /a>

Here is the example:

document.getElementsByTagName("html").foo="bar"

Here is another example how to set custom attributes into body tag element:

document.getElementsByTagName('body')[0].dataset.attr1 = "foo";
document.getElementsByTagName('body')[0].dataset.attr2 = "bar";

Then read the attribute by:

attr1 = document.getElementsByTagName('body')[0].dataset.attr1
attr2 = document.getElementsByTagName('body')[0].dataset.attr2

You can test above code in Console in DevTools, e.g.

JS Console, DevTools in Chrome

尐偏执 2024-08-18 07:58:44

是的,您可以使用 data-* 属性。
data-* 属性用于存储页面或应用程序私有的自定义数据。

<ul>
    <li data-pageNumber="1"> 1 </li>
    <li data-pageNumber="2"> 2 </li>  
    <li data-pageNumber="3"> 3 </li>  
</ul

Yes, you can use data-* attribute.
The data-* attribute is used to store custom data private to the page or application.

<ul>
    <li data-pageNumber="1"> 1 </li>
    <li data-pageNumber="2"> 2 </li>  
    <li data-pageNumber="3"> 3 </li>  
</ul

出色地!实际上,您可以通过将数据属性伪装成您真正想要的内容来创建一堆自定义 HTML 属性。

例如。

[attribute='value']{
   color:red;
}
<span attribute="value" >hello world</span>

它显然有效,但这会使您的文档无效,除非必须,否则不需要使用 JScript 来拥有自定义属性甚至元素,您只需要像对待您的新公式化(自定义)属性一样对待您的新制定(自定义)属性“数据”属性

记住“无效”并不意味着任何事情。该文档始终可以正常加载。
有些浏览器实际上只会通过 DOCTYPE 的存在来验证您的文档......,您实际上知道我的意思。

well! you can actually create a bunch of custom HTML attributes by disguising the data attributes in what you actually want.

eg.

[attribute='value']{
   color:red;
}
<span attribute="value" >hello world</span>

It apparently works but that would invalidate your document, there is no need of using JScript for you to have custom attributes or even elements unless you have to, you just need to treat your new formulated(custom) attributes just the same way you treat your "data" attribute

Remember "invalid" does not mean anything. The document will load fine at all the time.
and some browsers would actually validate your document only by the presence of DOCTYPE....., you actually know what I mean.

冷弦 2024-08-18 07:58:44

另一种干净且保持文档有效的方法是将您想要的数据连接到另一个标签(例如 id)中,然后使用 split 在您需要时获取您想要的数据。

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>

Another approach, which is clean and will keep the document valid, is to concatenate the data you want into another tag e.g. id, then use split to take what you want when you want it.

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>
若言繁花未落 2024-08-18 07:58:44

我可以想到自定义标签 "init" 的一个方便用途。包含一个在 document.onLoad() 时求值并为标签提供值的 JavaScript 表达式,例如,

<p><p>The UTC date is <span init="new Date().toUTCString()">?</span>.<p></p>

某些样板 JavaScript 代码会在 document.onload( ) 查找 init 属性、评估它们包含的表达式并将它们分配给包含标签的innerHTML 的时间。这将使 HTML 具有 JSP、PHP 等的一些功能。目前,我们必须将 HTML 标记和解释它的 JavaScript 代码分开。 Bug 喜欢分割代码。

I can think of a handy use for the custom tag "init". Include a JavaScript expression that gets evaluated at document.onLoad() time and provides a value for the tag, e.g.

<p><p>The UTC date is <span init="new Date().toUTCString()">?</span>.<p></p>

Some boilerplate JavaScript code would scan all the tags in the DOM at document.onload() time looking for the init attributes, evaluating the expressions that they contain, and assigning them to the containing tag's innerHTML. This would give HTML some of the power of JSP, PHP etc. Currently we have to split the HTML markup and the JavaScript code that illuminates it. Bugs love split code.

深海里的那抹蓝 2024-08-18 07:58:44

您可以添加,但随后您还必须编写一行 JavaScript 代码,

document.createElement('tag');

以确保一切都到位。我的意思是 Internet Explorer :)

You can add, but then you have to write a line of JavaScript code too,

document.createElement('tag');

to make sure everything fall in place. I mean Internet Explorer :)

绮筵 2024-08-18 07:58:44

您可以执行以下操作来从 JavaScript 而不是属性中提取所需的值:

<a href='#' class='click'>
    <span style='display:none;'>value for JavaScript</span>some text
</a>

You can do something like this to extract the value you want from JavaScript instead of an attribute:

<a href='#' class='click'>
    <span style='display:none;'>value for JavaScript</span>some text
</a>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文