【问题标题】:Jquery Change Image on selections on ajax html changesJquery Change Image on selections on ajax html changes
【发布时间】:2012-08-02 11:30:41
【问题描述】:

我正在尝试在选择不同颜色时更改产品图片。当我使用直接 HTML 时,我的 jQuery 代码可以正常工作,但是当我尝试使用 Ajax 所做的选择更改图像时,只有第一个选择有效。似乎我的 jQuery 只读取初始 html 而不是初始加载后所做的更改。我以为.on 会处理更新的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);        
}
 });});

【问题讨论】:

  • jQuery(this).find().val(); 找到什么?
  • 选项的值
  • find() 在被选元素的上下文中找到一个元素,这种情况下不需要使用它,你应该删除它。

标签: jquery dom refresh selection


【解决方案1】:

我能够使用 Brandon Aaron 的 livequery 插件来完成我想做的事情。我的印象是 livequery 插件只适用于旧版本的 jQuery 原来我错了它适用于 1.7.1 仍然不知道为什么 .on 不起作用。

【讨论】:

    【解决方案2】:

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

    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/

    【讨论】:

    • 感谢您的帮助和教育。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2013-05-02
    相关资源
    最近更新 更多