更新HTML元素中的文本而不删除其他元素(仅适用于jQuery)

时间:2018-11-14 23:39:14

标签: javascript jquery html

如何? 我知道有解决方案,但我想知道jQuery是否提供了一个不带本机Javascript函数的仅jQuery解决方案来执行以下操作。

什么? 假设我们具有以下HTML,并且我们想使用“ testDiv”类更改div的文本。我知道这是不好的HTML,因为在另一个HTML标签中有一个HTML标签以及纯文本。

React.createElement("div", {id: "queue-list-content", className: "queue-list-content", onScroll: this.handleScroll}

handleScroll: function(){
  //trying to call function that lives in the file with the rest of the API calling functions here
}
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

int main() {
  if(glfwInit()==false)
    cout<<"FAILED";
}

您找到没有本机Javascript函数的方法吗?

我是对的,这不能仅通过使用jQuery函数来完成,因为它是一个节点吗? jQuery没有内置功能吗?

3 个答案:

答案 0 :(得分:1)

您可以使用first()代替[0],并使用contents()获取所有子项,包括文本节点。但是,我不知道会执行.data = <new value>操作的jQuery方法,因此,如果该方法不存在,则可以使用get()来更改textNode。

setTimeout(function() {
  $('.testDiv').first().contents().get(1).data = "1";
}, 500);
setTimeout(function() {
  $('.testDiv').first().contents().get(1).data = "2";
}, 900);

setTimeout(function() {
  var $el = $('.testDiv'),
    $preStuff = $el.find('span').clone(true);
  $el.text('3').prepend($preStuff);

}, 1300);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testDiv"><span>I like it </span> Hello World </div>

答案 1 :(得分:1)

jQuery没有专门用于隔离文本节点的方法,但是一旦隔离,您可以将它们包装在$()中,并使用诸如replaceWith()wrap()之类的方法,并将其转变为标记元素,并使用诸如text()替换

var $el =  $('.testDiv').contents().last().wrap('<span>').parent()

setTimeout(function() {
 $el.text('1')
}, 500);
setTimeout(function() {
  $el.text('2')
}, 900);

setTimeout(function() {      
  $el.text('3');
}, 1300);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testDiv"><span>I like it </span> Hello World </div>

答案 2 :(得分:-2)

您可以使用以下代码在该div中更改html:

$('。testDiv')。html('div内的新文本');