jquery更改P的innerhtml不起作用 [英] jquery changing innerhtml of a P isn't working

查看:146
本文介绍了jquery更改P的innerhtml不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为使用jQuery可以轻松更改段落上的某些文本.它可以完美地完成传统方式,即

I have what I thought was a simple select with jQuery to change some text on a paragraph. It works perfect the traditional way i.e.

document.getElementById('message_text').innerHTML = "hello";

但是使用jQuery却没有.我已经检查了$('#message_text')的值,并且确定我看到了这些项目.

But with jQuery it doesn't. I have checked the values of $('#message_text') and sure enough I see the items.

$('#message_text').innerHTML = "hello";

我做错什么了吗?

有人有什么主意吗?

推荐答案

当执行类似$('#message_text')的操作时,没有常规的DOM对象,而是jQuery包装的集(即使在这种情况下,只能是一个元素.)如果要访问特定的DOM属性,则可以执行以下操作:

When you do something like $('#message_text') what you have there is not a regular DOM object, but a jQuery wrapped set (even though in this case it'd only be one element.) If you wanted to access a particular DOM property, you could do this:

$('#message_text')[0].innerHTML = 'whatever';
$('#message_text').get(0).innerHTML = 'whatever';

但是,在这种情况下这不是必需的,因为jQuery有两个函数可以执行您想要的操作:

However, this isn't necessary in this case as jQuery has two functions to do what you want:

html() :

$('#message_text').html('whatever');

text() :

$('#message_text').text('whatever');

两者之间的区别是html()将允许HTML,而text()将转义传递给它的所有HTML标记.使用您需要的内容而不是使用innerHTML手动处理HTML.

The difference between the two is that html() will allow HTML while text() will escape any HTML tags you pass to it. Use the one you need over manually manipulating the HTML with innerHTML.

这篇关于jquery更改P的innerhtml不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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