我写了一个简单的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');
}
});
答案 0 :(得分: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');
}
});
});
答案 1 :(得分:1)
$(function() {
$('h1:contains("123")').text('hi');
$('h1:contains("456")').text('hi2');
});
答案 2 :(得分:0)
这样做:
$(document).ready(function() {
var change = {
'123': 'hi',
'456': 'hi2'
};
$('h1').text(function(i, txt) {
return change[$.trim(txt)];
});
});