[英]Javascript find and replace dom string
I want to use replace method of javascript to replace some html string.我想使用javascript的replace方法来替换一些html字符串。 I stored a dom string by fetching .outerHTML and want to replace a perticular word with the string.
我通过获取 .outerHTML 存储了一个 dom 字符串,并想用该字符串替换一个特定的单词。 Here is my outerHTML dom which i fetch with javascript :
这是我用javascript获取的outerHTML dom:
<figure class="image" onclick="someMethod('btbjwkjpuynyzdijsvf5.jpg', 'Title','$caption', 'image','other params')">
<img id="45435435345" src="btbjwkjpuynyzdijsvf5.jpg" caption="$caption" title="title">
<figcaption>$caption</figcaption>
</figure>
Here is want to replace all $caption with real caption which i fetch from database later.这是想用我稍后从数据库中获取的真实标题替换所有 $caption 。 But this is not working.
但这是行不通的。 I tried on browser console to store this string on variable but it giving error after single quote (which is available inside function parameter).
我尝试在浏览器控制台上将此字符串存储在变量上,但它在单引号(在函数参数中可用)后给出错误。 So i think it is having a problem with unrecognized string value.
所以我认为它存在无法识别的字符串值的问题。 How can i resolve this issue so i can replace $caption value from string.
我该如何解决这个问题,以便我可以从字符串中替换 $caption 值。
This is not a good practice but instead you can use a javascript templating engine这不是一个好的做法,但您可以使用 javascript 模板引擎
$("#myDiv").html($("#myDiv").html().replace(/\\$caption/g,'My caption'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myDiv"> <figure class="image" onclick="someMethod('btbjwkjpuynyzdijsvf5.jpg', 'Title','$caption', 'image','other params')"> <img id="45435435345" src="btbjwkjpuynyzdijsvf5.jpg" caption="$caption" title="title"> <figcaption>$caption</figcaption> </figure> </div>
I would use the attribute selector我会使用属性选择器
$("[caption]").attr("caption", myCaptionText)
you should ofcourse be a bit more specific so you don't over write every instance of the caption attribute你当然应该更具体一点,这样你就不会覆盖标题属性的每个实例
$(".specificParent [caption]").attr("caption", myCaptionText)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.