[英]How to change sibling text of element without changing html using jQuery?
I'm trying to replace text only, but without touching any other tags. 我正在尝试仅替换文本,但不触摸任何其他标签。
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Login
</a>
</p>
$('p').each(function() {
$(this).text($(this).text.replace('Login', 'Anmeldung'));
});
Bad result: 不良结果:
<p>
Anmeldung
</p>
Result as I would like it to be: 我希望得到的结果是:
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Anmeldung
</a>
</p>
How can I do this? 我怎样才能做到这一点? This is only a sample, deeper structure of
p
tags can be completely different. 这只是一个示例,
p
标签的更深层次结构可以完全不同。
Wrap text you want to replace in a span or something. 将要替换的文本换成跨度或其他内容。
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
<span class="replace-login">Login</span>
</a>
</p>
and js 和js
$('.replace-login').each(function() {
$(this).text($(this).text.replace('Login', 'Anmeldung'));
});
Use .html()
instead of .text()
使用
.html()
而不是.text()
This preserves your html tags 这会保留您的html标签
$('p').each(function() { $(this).html($(this).html().replace('Login', 'Anmeldung')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <a href="login.php"> <i class="fa fa-sign-in"></i> Login </a> </p>
If you want to change all text sibling of i
, select i
tag in p
and use Node.nextSibling
property to selecting sibling text after element and change it. 如果要更改
i
所有文本同级,请在p
选择i
标记,并使用Node.nextSibling
属性在element之后选择同级文本并进行更改。
$("p > a > i")[0].nextSibling.nodeValue = "Anmeldung";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <a href="login.php"> <i class="fa fa-sign-in"></i> Login </a> </p>
But if you want to replace part of text, use this code 但是,如果要替换部分文本,请使用此代码
$("p > a").html(function(i, html){ return html.replace("Login", "Anmeldung"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <a href="login.php"> <i class="fa fa-sign-in"></i> Login </a> </p>
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Login
</a>
</p>
$('p').each(function() {
$(this).find("a").text($(this).find("a").text.replace('Login', 'Anmeldung'));
});
You can try this DEMO LINK HERE 您可以在此处尝试此演示链接
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Login
</a>
</p>
JS.. JS ..
$('p').each(function() {
$(this).html($(this).html().replace('Login', 'Anmeldung'));
});
http://jsfiddle.net/hnfRe/402/
http://jsfiddle.net/hnfRe/402/
use html instead of text function. 使用html而不是文字功能。 .
。 .
。
$('p').html($(this).html().replace('Login', 'Anmeldung'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.