0
<p id="test">lol</p>

<script type="text/javascript">
var text = $('test').text();
var comparingText = 'lol';

if (text == comparingText) {
document.write('haha');
}
</script>

为什么这行不通?甚至尝试过使用“ IF NOT”..

4

2 回答 2

4

您正在尝试获取<test>标签,而不是带有 ID 的标签test。要通过 ID 获取标签,您需要一个#符号:$('#test')

但是:使用 jQuery 作为选择引擎是矫枉过正且效率低下。这是您在 vanilla JavaScript 中的代码:

if( document.getElementById('test').firstChild.nodeValue == "lol")
  document.write("haha");
于 2012-12-15T06:41:01.003 回答
0

您没有通过 id 获取元素,应该是:

var text = $('#test').text();

最好在 DOM 加载事件中编写脚本:

$(function(){
    var text = $('#test').text();
    var comparingText = 'lol';

    if (text == comparingText) {
        document.write('haha');
    }
);

小提琴:http: //jsfiddle.net/eedUs/1/

于 2012-12-15T06:42:03.907 回答