简体   繁体   English

如何在JavaScript字符串之间附加内容?

[英]How to append something between a javascript string?

I have a HTML structure like this: 我有这样的HTML结构:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<table id ="x">
  <tr>
    <td class='col1'>
      Hello <span class='name'></span> How are u ?
    <td>
  </tr>
</table>

And here is my jQuery code: 这是我的jQuery代码:

var variable = $('table#x').find(".col1").html().find("span.name").append(' Jack..!').replace('u', 'you');
alert(variable);

Now, I want this output: 现在,我想要这个输出:

<td class='col1'>Hello <span class='name'>Jack..!</span> How are you ?<td>

How can I do that? 我怎样才能做到这一点?

You already have a class you can target, 'name'. 您已经有了可以定位的类“名称”。 You can simply add the text to this: 您可以简单地在其中添加文本:

$('.name').text('Jack..!')

https://jsfiddle.net/2j7rxwyj/ https://jsfiddle.net/2j7rxwyj/

Based on my comment , you could use the following: 根据我的评论 ,您可以使用以下内容:

Updated Example 更新示例

$('table#x .col1 span.name').append(' Jack..!').parent().text(function () {
  return $(this).text().replace('u', 'you');
});

There were a couple issues in your code. 您的代码中有几个问题。 For one, you can't chain .append() after the .html() method. 例如,您不能在.html()方法之后链接.append() In addition, the .replace() method wasn't changing the text. 此外, .replace()方法不会更改文本。 To fix this, you could pass an anonymous function to the .text() method and return the replaced text. 要解决此问题,您可以将匿名函数传递给.text()方法,然后返回替换的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM