如何在不使用jQuery更改html的情况下更改元素的兄弟文本? [英] How to change sibling text of element without changing html using jQuery?

查看:80
本文介绍了如何在不使用jQuery更改html的情况下更改元素的兄弟文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅替换文字,但不接触任何其他标签。

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')); 
});

结果不好:

<p>
    Anmeldung       
</p>

我想要的结果是:

<p>
    <a href="login.php">
        <i class="fa fa-sign-in"></i> 
        Anmeldung
    </a>
</p>

我该怎么做?这只是一个示例, p 标签的更深层结构可能完全不同。

How can I do this? This is only a sample, deeper structure of p tags can be completely different.

推荐答案

使用 .html()而不是 .text()

此保留你的html标签

Use .html() instead of .text()
This preserves your html tags

$('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>

小提琴 使用您的示例。

Fiddle using your example.

这篇关于如何在不使用jQuery更改html的情况下更改元素的兄弟文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆