假设我将以下字符串存储在变量中,比如txt1
:
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscs" href="javascript:void(0)">1. fcfs.cs</a> <i id="myStaroperatingsystemsrcfirstcomefirstservefcfscs" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscpp" href="javascript:void(0)">2. fcfs.cpp</a> <i id="myStaroperatingsystemsrcfirstcomefirstservefcfscpp" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfspy" href="javascript:void(0)">3. fcfs.py</a> <i id="myStaroperatingsystemsrcfirstcomefirstservefcfspy" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfsrs" href="javascript:void(0)">4. fcfs.rs</a> <i id="myStaroperatingsystemsrcfirstcomefirstservefcfsrs" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstserveFCFSjava" href="javascript:void(0)">5. FCFS.java</a> <i id="myStaroperatingsystemsrcfirstcomefirstserveFCFSjava" class="fa fa-star"></i><br>
现在我想在字符串中的每个style='color: rgb(255, 255, 255); font-weight: bold'
之后插入a target="_blank
。
我怎样才能使用javascript?
答案 0 :(得分:1)
如果您可以轻松使用CSS来设置相应元素的样式,为什么要使用Javascript来修改HTML字符串:
a[target="_blank"] + * {
color: /* rgb(255, 255, 255) */
red;
font-weight: bold;
}
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscs" href="javascript:void(0)">
1. fcfs.cs
</a>
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfscs" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscpp" href="javascript:void(0)">
2. fcfs.cpp
</a>
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfscpp" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfspy" href="javascript:void(0)">
3. fcfs.py
</a>
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfspy" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfsrs" href="javascript:void(0)">
4. fcfs.rs
</a>
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfsrs" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstserveFCFSjava" href="javascript:void(0)">
5. FCFS.java
</a>
<i id="myStaroperatingsystemsrcfirstcomefirstserveFCFSjava" class="fa fa-star"></i><br>
答案 1 :(得分:0)
如果我绝对必须这样做,我会使用String#replace
。但我会先尝试很难找到基于CSS的解决方案。
const substring = 'a target="_blank"'
const replacement = '$& style="color: rgb(255, 255, 255); font-weight: bold"'
txt1.replace(substring, replacement)