繁体   English   中英

.text()影响h1内的html元素

[英].text() affects html elements inside h1

我有以下标记:

<h1>A text <span class="createTask glyphicon glyphicon-plus"></span></h1>

我要做的是双击h1更改其文本。 为此,我在文档就绪函数中编写了以下代码

$("h1").on("dblclick",function(){
   var newTitle = prompt("Enter a new title");
  if(newTitle){
     $(this).text(newTitle);
  }

})

但是,此代码不只是更改h1的文本,而是删除了glyphicon跨度。 任何想法为什么? 请注意,我无法更改标记

使用$(this).text() (. .html()是正确的语法),您正在更改整个h1内容,包括其中的字形。

如果要保留字形(带有跨度),则将它们与h1分开,如下所示:

<h1>A text </h1><span class="createTask glyphicon glyphicon-plus"></span>

或者,根据您的要求-无需更改标记:

$(this).html(newTitle + "<span class='createTask glyphicon glyphicon-plus'>");

您需要更新h1的第一个文本节点: $(this).contents().get(0).nodeValue = newTitle;

 $("h1").on("dblclick", function() { var newTitle = prompt("Enter a new title"); if (newTitle) { $(this).contents().get(0).nodeValue = newTitle; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <h1>A text <span class="createTask glyphicon glyphicon-plus"></span></h1> 

h1元素内添加另一个范围,然后

<h1>
    <span id="text">A text </span>
    <span class="createTask glyphicon glyphicon-plus"></span>
</h1>

$("h1").on("dblclick",function() {
    var newTitle = prompt("Enter a new title");
    if (newTitle){
        $(this).find('#text').text(newTitle);
    }

})

您可以使用Node.previousSibling获取SPAN DOM元素的先前同级,然后可以设置其nodeValue

 $("h1").on("dblclick", function() { var newTitle = prompt("Enter a new title"); if (newTitle) { var span = $(this).find('span').get(0); //get the DOM element span.previousSibling.nodeValue = newTitle; } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <h1>A text <span class="createTask glyphicon glyphicon-plus">+++++</span></h1> 

.text()用指定的文本替换元素的内容。 由于图标范围位于元素内部,因此它将被替换。
您可以直接定位文本节点并替换其文本。

this.firstChild.nodeValue = newTitle;

暂无
暂无

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

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