使用場景:微信小程序
具體功能:從服務器獲取文章內容 展示在小程序里
使用語言: C#
---------------------------------------------------------
因為微信小程序不能識別html標簽,不能直接獲取到html綁定到小程序里
有兩種解決方案:
1、使用基於微信小程序的第三方插件。
2、在服務器后 直接把html處理好,返回。
本篇文章說的 是第二個方法
---------------------------------------------------------
解決思路:
1.定義一個數組
2.獲取html內容,根據p標簽或者div標簽 分割 (這里解釋一下,內容一般是后台使用編輯器填的,生成的標簽段落都是p標簽為主,所以我 這里用p標簽分割)
3.循環分割的html,判斷有沒有包含img標簽
4.過濾p標簽 和 圖片 保存在數組里。
5.返回給小程序,前台判斷綁定。
---------------------------------------------------------
//定義一個類型,用來保存分割后的內容 public class CntList { public string content { get; set; } public string type { get; set; } } /// <summary> /// 具體實現的方法 /// </summary> /// <param name="content">文字內容</param> /// <returns>listCnt</returns> public static List<CntList> getCntByList(string content) { List<CntList> listCnt = new List<CntList>(); //文章 if (!string.IsNullOrEmpty(content)) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(content); var p_cnt = doc.DocumentNode.SelectNodes("//p"); foreach (var pItem in p_cnt) { var node = HtmlNode.CreateNode(pItem.OuterHtml); if (node.InnerHtml.Contains("src")) { if (node.SelectSingleNode("//img") != null) { string _href = node.SelectSingleNode("//img").Attributes["src"].Value; listCnt.Add(new CntList { type = "image", content = _href }); } } else { listCnt.Add(new CntList { type = "content", content = X.Component.Tools.StringHelper.NoHTML(node.InnerText) }); } } } return listCnt; }
微信小程序綁定數據:
<view class="detail-info"> <view wx:for="{{detail.cnt}}" wx:for-item="cntItem" style=" margin-bottom: 15px;" wx:key="shardCnt"> <block wx:if="{{cntItem.type=='image'}}"> <image src="{{cntItem.content}}" mode="aspectFill" class="cover"></image> </block> <block wx:else> <view>{{cntItem.content}}</view> </block> </view> </view>
效果: