繁体   English   中英

使用jQuery更改标签的属性

[英]Changing the attribute of a tag with jquery

我有这个HTML代码,我想用jQuery编辑。 这是HTML。

<html> 
  <head> 
    <title>JQuery Problem 1</title> 
    <script type="text/javascript" src="jquery-1.4.min.js"></script> 
    <script type="text/javascript" src="problem1.js"></script> 
  </head> 
  <body> 
    <ol> 
      <li>Comp 250
        <ul> 
          <li>HTML</li> 
          <li>CSS</li> 
          <li>CGI</li> 
          <li>PHP</li> 
          <li>JavaScript</li> 
        </ul> 
      </li> 
      <li>Comp 345
        <ul> 
          <li>Objects and classes</li> 
          <li>Static and constant members</li> 
          <li>Operator overloading</li> 
          <li>Templates</li> 
          <li>Inheritance</li> 
          <li>Polymorphism</li> 
        </ul> 
      </li> 
      <li>Comp 431
        <ul> 
          <li>Perl language</li> 
          <li>File uploads and downloads</li> 
          <li>AJAX and JSON</li> 
          <li>Java Servlets</li> 
          <li>JSP</li> 
        </ul> 
      </li> 
    </ol> 
  </body> 
</html> 

我想做的是编辑Ol列表的列表标签。 所以我要编辑的标签是

<li>Comp 250
<li> Comp 345
<li> Comp 431

this is how i want them to be
 <li style="margin: 1em; font-weight: bold">Comp 250
  <li style="margin: 1em; font-weight: bold">Comp 245
    <li style="margin: 1em; font-weight: bold">Comp 431

一些东西:

  1. 使用css()设置样式属性;
  2. 因为<ul>在list元素内,所以粗体也将应用于子list元素。

因此,您有两种选择:

  1. 将文本换成<span> 要么
  2. 将字体粗细设置为粗体,然后将子列表元素设置为普通字体粗细。

对于第一个,仅获取文本节点有些棘手,但是可以做到。 尝试:

$("ol > li").each(function() {
  $($(this).contents()[0]).wrap("<span>").parent()
    .css({margin: "1em", fontWeight: "bold"});
});

输出为:

<ol>
  <li><span style="margin: 1em; font-weight: bold;">Comp 250 </span>
    <ul>
      <li>HTML</li>
      <li>CSS</li>
      <li>CGI</li>
      <li>PHP</li>
      <li>JavaScript</li>
    </ul>
  </li>
  <li><span style="margin: 1em; font-weight: bold;">Comp 345 </span>
    <ul>
      <li>Objects and classes</li>
      <li>Static and constant members</li>
      <li>Operator overloading</li>
      <li>Templates</li>
      <li>Inheritance</li>
      <li>Polymorphism</li>
    </ul>
  </li>
  <li><span style="margin: 1em; font-weight: bold;">Comp 431 </span>
    <ul>
      <li>Perl language</li>
      <li>File uploads and downloads</li>
      <li>AJAX and JSON</li>
      <li>Java Servlets</li>
      <li>JSP</li>
    </ul>
  </li>
</ol>

或者,您可以更改内部列表上的字体粗细:

$("ol > li").css({margin: "1em", fontWeight: "bold"})
  .find("ul").css({fontWeight: "normal"});

暂无
暂无

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

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