我正在使用JQuery来修改和替换以下HTML
<div class="weather-feed">
<img src="http://l.yimg.com/a/i/us/we/52/32.gif"/><br />
<b>Current Conditions:</b><br />
Sunny, 17 C<BR />
<BR /><b>Forecast:</b><BR />
Wed - Mostly Sunny. High: 27 Low: 14<br />
Thu - Mostly Sunny. High: 25 Low: 14<br />
Fri - Partly Cloudy. High: 26 Low: 15<br />
Sat - Partly Cloudy. High: 27 Low: 17<br />
Sun - Partly Cloudy. High: 28 Low: 17<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Pretoria__SF/*http://weather.yahoo.com/forecast/SFXX0044_c.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>
</div>
通过PHP会话将此代码检索到页面上(特别是div)。 div就是帮助选择(以及后来的样式)。
因为很多HTML没有任何可识别的容器,我使用正则表达式来隔离某些文本(例如天气状况和预测):
$(document).ready(function() {
var src = $(".weather-feed");
// remove line feeds
src.find("br").remove();
// get weather conditions
var result = "<div class=\"weather-conditions\">";
result += src.html().match(/<\/b>([^<]*)<b>/)[1].trim();
result += "</div>";
// get weather icon
result += "<div class=\"weather-icon\"><img src=\"" + src.find("img").attr("src") + "\" /><span><?php echo($city); ?></span></div>";
// more button
result += "<div class=\"weather-more-button\">+</div>";
// get weather forecast
result += "<div class=\"weather-extra\">";
result += "<div class=\"weather-forecast\">";
result += src.html().match(/<\/b>([^<]*)<a/)[1].trim().replace("\n", "<br />");
result += "</div>";
// get addition forecast link
result += "<div class=\"weather-detail\">";
result += $("<div/>").html(src.find('a').first()).html();
result += "</div></div>";
console.log(result);
// write new code to page
src.empty();
src.append(result);
});
不幸的是,虽然jquery没有产生错误并且正确地将result
记录到控制台(见下文),但新代码不会呈现给页面。所有我看到的仍然是PHP返回的原始代码。
<div class="weather-conditions">
Sunny, 17 C
</div>
<div class="weather-icon">
<img src="http://l.yimg.com/a/i/us/we/52/32.gif" />
<span>Pretoria</span>
</div>
<div class="weather-more-button">+</div>
<div class="weather-extra">
<div class="weather-forecast">
Wed - Mostly Sunny. High: 27 Low: 14<br />
Thu - Mostly Sunny. High: 25 Low: 14
Fri - Partly Cloudy. High: 26 Low: 15
Sat - Partly Cloudy. High: 27 Low: 17
Sun - Partly Cloudy. High: 28 Low: 17
</div>
<div class="weather-detail">
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Pretoria__SF/*http://weather.yahoo.com/forecast/SFXX0044_c.html">Full Forecast at Yahoo! Weather</a>
</div>
</div>
此外(我认为这很有可能是相关的),在天气预报部分下用\n
替换<br />
并不比第一场比赛更有效,而且我在失去了为什么会这样。
如果有人能以任何方式在这里提供帮助,我真的很感激。
这是一个小提琴,所以你可以看到发生了什么:http://jsfiddle.net/4UyAj/