2012-08-04 45 views
0

我试图在选择不同颜色时更改产品图片。当我使用直接的HTML时,我的jQuery代码工作正常,但是当我尝试用仅使用Ajax进行的选择更改图像时,只有第一个选择可行。看来,我的jQuery只读取最初的HTML,而不是在初始加载后所做的更改。我认为.on将处理更新的HTML,但我似乎失去了一些东西。任何指导将不胜感激。jquery更改ajax html选项上的选择图片

jQuery(window).load(function(){ 
    var data = { 
    "1" : { img: "/test.png" }, 
    "2" : { img: "/test_1.png" }, 
    "3" : { img: "/test_2.png" }, 
    }; 
    jQuery('[name*="Color"]').on('change',function() { 
var value = jQuery(this).val(); 
if (data[value] != undefined) 
{ 
    jQuery('#product-image').attr('src', data[value].img);   
} 
});}); 
+0

'的jQuery(这) .find()。val();'_find_什么? – undefined 2012-08-04 22:07:53

+0

选项的值 2012-08-04 22:30:21

+1

find()在所选元素的上下文中找到一个元素,在这种情况下不需要使用它,你应该删除它。 – undefined 2012-08-04 22:34:35

回答

0

我能够使用Brandon Aaron的livequery插件来完成我正在尝试做的事情。我的印象是,这个livequery插件只适用于老版本的jQuery,结果我错了,它在1.7.1下很好用。仍然不知道为什么.on不起作用。

0

将新节点插入文档后,您需要重新进行事件绑定。尝试插入代码:

jQuery('[name*="Color"]').on('change',function()... 

在加载函数回调中。

编辑:

我现在是你的窗口文件中注册的加载事件实现...你做错了......你需要下载新的节点,将它们插入并登记他们的活动。

你需要做的是这样的:

$("#idOfTheElementThatWillContainTheNewNodes").load(
    "url to obtain the code to be inserted", 
    { param1: value1, ..., paramN : valueN }, // parameters to be sent to the server (if any) 
    function(responseText, textStatus, xmlHttpRequest) { // this is the load callback. it will run after the request is complete 
     // ok, the responseText was inserted in "idOfTheElementThatWillContainTheNewNodes" container. 
     // now you do register your events... 
    } 
); 

您可以在文档看看:http://api.jquery.com/load/

我创建了一个例子给你,我们来看一看:http://jsfiddle.net/davidbuzatto/zuFsc/

+0

我欣赏帮助和教育。 – 2012-08-08 21:58:34

+0

@JohnPhelan:不客气! – davidbuzatto 2012-08-08 22:50:39