0

我写了一个简单的 if 条件,但不是很有效。如果文本是 123 更改为 hi,如果文本是 456 将其更改为 hi2 有人可以帮我一把吗?

    <h1>123</h1>
    <h1>456</h1>
    <h1>789</h1>​


$(document).ready(function() {

    var changeText1 = '123';
    var changeText2 = '456';
    var text = $(h1).text();

    if (text == changeText) {
        $(this).text('hi');
    } else if (text == changeText2 ) {
        $(this).text('hi2');
    }

});

​</p>

http://jsfiddle.net/8P2ma/

4

3 回答 3

2

您的代码有很多问题:

$(document).ready(function() {

    var changeText1 = '123';
    var changeText2 = '456';
    var text = $(h1).text(); //aside from having to iterate through, the jquery
                             //selector needs to be enclosed in quotes: $('h1')
    if (text == changeText) { //The variable 'changeText' does not exist.
        $(this).text('hi');
    } else if (text == changeText2 ) {
        $(this).text('hi2');
    }

});

//working code:
$(document).ready(function() {

    var changeText1 = '123';
    var changeText2 = '456';

    $('h1').each(function() {
        var text = $(this).text();
        if (text == changeText1) {
            $(this).text('hi');
        } else if (text == changeText2) {
            $(this).text('hi2');
        }
    });
});​
于 2012-10-30T22:59:01.210 回答
1
$(function() {
    $('h1:contains("123")').text('hi');
    $('h1:contains("456")').text('hi2');
});​

小提琴

于 2012-10-30T23:00:45.073 回答
0

像这样做:

$(document).ready(function() {
    var change = {
        '123': 'hi',
        '456': 'hi2'
    };
    $('h1').text(function(i, txt) {
        return change[$.trim(txt)];
    });
});

演示:http: //jsfiddle.net/By4Ra/

于 2012-10-30T22:56:48.740 回答