jQuery html函数没有't使用对象作为参数

jQuery html function doesn't work with object as parameter

本文关键字:对象 参数 函数 html jQuery      更新时间:2023-09-26

在我的应用程序中,图片的html保存在itemConfig.picture

如果我将以下代码添加到js:

$('.picture').html(itemConfig.picture);

picture的div保持为空。但这个有效:

var tmpVar='<div class="field field-name-field-picture field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img typeof="foaf:Image" src="http://localhost/ae/sites/default/files/DSC_02911_0.jpg" width="130" height="120" alt="" /></div></div></div>'
$('.picture').html(tmpVar);

这些信息将是有用的:

alert(typeof itemConfig.picture); // returns "String"
alert(itemConfig.picture); // returns <div class="field field-name-field-picture field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img typeof="foaf:Image" src="http://localhost/ae/sites/default/files/DSC_02911_0.jpg" width="130" height="120" alt="" /></div></div></div>

为什么传递对象属性不起作用?

我认为这对你有用,但这只是猜测。

$('.picture').html(itemConfig.picture.toString());

您应该不需要.toString(),正如您在Fiddle中看到的那样。

var itemConfig = {};
itemConfig.picture = "<div style='width: 20px; height: 20px; background-color: red'></div>";
$('#start').on('click', function () {
    $('#type').html(typeof itemConfig.picture);
    $('#length').html($('.picture').length);
    $('.picture').html(itemConfig.picture);
});

评论中的假设似乎是正确的。此时dom(picture.length = 0)中没有picture类的元素,或者itemConfig.picture的值是其他值。