使用Javascript或其他任何内容更改HTML元素内的文本

时间:2014-05-03 23:04:17

标签: javascript php jquery html

有人可以帮我改变HTML标签内的文字

例如,在我的正文页面加载页面时显示

<td>Hello</td>

我只想改变那个文字&#34;你好&#34;到&#34;嗨&#34;准备好的功能没有onclick

另一个例子,我知道javascript上有一些如何,如果在td中等于&#34;你好&#34;然后将其改为&#34;嗨&#34;。

如果还有一些解决方案,那么if ... else函数会更好

感谢。

3 个答案:

答案 0 :(得分:1)

使用jQuery:

$(function(){
     $('#tdID').text('Hi');
});

或有前提条件:

$(function(){
    if($('#tdID').text() == 'Hello'){
        $('#tdID').text('Hi');
     }
});

<强>更新

要使此代码生效, 必须 td嵌套在tr内,table应嵌套在{{ 1}}:

<table>
    <tr>
        <td id="myID">Hello</td>
    </tr>
</table>

查看实时示例here

完整代码:

<html>
<head>
<title>jQuery text's attribute demo</title>
</head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
    if($('#myID').text() == 'Hello'){
        $('#myID').text('Hi');
    }
});
</script>
<body>
<table>
    <tr>
        <td id="myID">Hello</td>
    </tr>
</table>
</body>
</html>

答案 1 :(得分:1)

HTML: <td id="myId">Hello</td>

JS:

 document.getElementById("myId").innerHTML="new text";

答案 2 :(得分:1)

这会将“Hello”更改为“Hi”:

$('td').text('Hi');

如果你给你的元素一个像这样的id:

<td id="myTD">Hello</td>

然后你可以只改变文字:

$('#myTD').text('Hi');

这将检查每个<td>是否为“Hello”并将其更改为“Hi”:

$( "td" ).each(function(index) {
  if( $(this).text() == "Hello" ) $(this).text('Hi');
});