[英]how to find string in html tag and replace using javascript/jquery
I do not know how to find a string in the html tag and replace it with another one. 我不知道如何在html标记中找到一个字符串并将其替换为另一个。 I will show it on an example. 我将在一个示例中展示它。
I have something like that 我有这样的东西
<a class="test" data-value="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>
And I would like to get such an effect 我想得到这样的效果
<a class="test"> <img-src="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>
Does anyone have any idea? 有人有什么主意吗? I'm sorry for my level of English. 我对我的英语水平感到抱歉。
You can first append
the img
and then remove the attribute data-value
. 您可以先append
img
,然后删除属性data-value
。
See the code below: 请参见下面的代码:
$("a").append(function(){ return '<img src="'+$(this).attr("data-value")+'">'; }).removeAttr("data-value")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="test" data-value="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>
Assuming that you are new in JavaScript
and/or jQuery
, I've made a step-by-step example of a solution: 假设您是JavaScript
和/或jQuery
新手,我逐步给出了解决方案的示例:
// create a pointer to your anchor
var $yourAnchor = $('.test')
// copy data attribute
var $hdata = $yourAnchor.data('value');
// remove attribute
$yourAnchor.removeAttr('data-value');
// insert html
$yourAnchor.html('<img src="' + $hdata + '">');
// If It has multiple hyperlink tag then $('a').each(function(){ if($(this).data('value')!=undefined){ $(this).append(function(){ return '<img src="'+$(this).attr("data-value")+'">'; }).removeAttr("data-value"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="test" data-value="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.