我正在从Ajax调用中检索XML响应,并且我正在尝试从来自XML的图像名称在我的数据列表中设置图像。这似乎是有问题的。我尝试设置图像的方式是这样的:
$(".Image", tablex).attr('src', product.find("Image").attr('src'));
但是,这似乎不起作用,因为在渲染结果中,我看到第一行第一项的图像正在我新添加的每个项目上复制/渲染。即使我像下面这样设置属性:
$(".Image", tablex).attr('123456');
结果与上面相同,所以我相信我在attr
中的代码没有效果!如果我像这样设置代码: $(".Image", tablex).html(product.find("Image").text());
然后我可以看到页面上呈现的正确文件名。
这是我的函数:
function OnSuccess(response) {
var xmlDoc = $.parseXML(response);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var customers = xml.find("Customers");
customers.each(function () {
var product = $(this);
var tablex = $("#dvProducts div").eq(0).clone(true);
$(".Image", tablex).attr('src', product.find("Image").attr('src'));// <- Problem is here!
$(".ProductID", tablex).html(product.find("ProductID").text());
$(".Name", tablex).html(product.find("Name").text());
$("#dvProducts").append(tablex);
});
}
我的数据列表
<div id="dvProducts">
<asp:DataList ID="rptCustomers" runat="server" BorderColor="Black" CellPadding="0" CellSpacing="0" RepeatLayout="Table" RepeatDirection="Horizontal" >
<ItemTemplate>
<div class="wrapping">
<div id="boxer">
<span class="Image"><asp:Image ID="Image" runat="server" CssClass="topimage" ImageUrl='<%# "~/images/topimages/" &Eval("Image")%>' /></span>
<br />
<span class="ProductID"><asp:Label ID="ProductID" runat="server" Text='<%# Eval("ProductID") %>' /></span>
<br />
<span class="Name"><asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>' /></span>
</div>
</div>
<br />
</ItemTemplate>
</asp:DataList>
</div>
XML 响应包含新三个项目的数据。
"<NewDataSet>
<Customers>
<RowNumber>4</RowNumber>
<SubCatName>Teenagers Phones</SubCatName>
<ProductID>6</ProductID>
<SubCategoryID>2</SubCategoryID>
<Name>HTC b</Name>
<Description>thcs</Description>
<Image>htc3.jpg</Image>
</Customers>
<Customers>
<RowNumber>5</RowNumber>
<SubCatName>Teenagers Phones</SubCatName>
<ProductID>5</ProductID>
<SubCategoryID>2</SubCategoryID>
<Name>HTC a</Name>
<Description>htca</Description>
<Image>htc2.jpg</Image>
</Customers>
<Customers>
<RowNumber>6</RowNumber>
<SubCatName>Teenagers Phones</SubCatName>
<ProductID>4</ProductID>
<SubCategoryID>2</SubCategoryID>
<Name>HTC</Name>
<Description>htc</Description>
<Image>htc1.png</Image>
</Customers>
<PageCount>
<PageCount>4</PageCount>
</PageCount></NewDataSet> "
也许相对路径干扰了某些东西,或者为什么我的attr
代码没有被拾取,而我在每个新项目上都得到相同的图像?有什么想法吗?
您在 XML 响应中只获得图像名称,因此您需要更新 <span>
中包含的 <img>
元素的 src
属性。但是 XML 不包含完整路径,因此还需要在映像名称前面附加路径。这样的事情应该有效:
// find the img tag within the span
// | set the src attribute of the image
// | | prepend the image path
// | | | get the image name from the xml
// | | | |
$(".Image", tablex).find('img').attr('src', '/images/topimages/' + product.find("Image").text());
请注意,ASP 标记中的"~/images"路径是在服务器端处理的,具有特殊含义,而 javascript 是客户端处理的。在大多数情况下,上面的代码应该可以工作,但 ASP.NET 允许您配置项目的"root"目录,因此您可能需要修改我的示例才能使其正常工作。