Jquery 地图不会检索选定的选项;总是空的?似乎跳过变量,适用于 jsfiddle,无控制台错误

Jquery map won't retrieve selected options; always empty? Appears to skip variable, Works on jsfiddle, No console errors

已解决:

最终 fiddle:

http://jsfiddle.net/AcfUz/220/

*使用了所选答案中指示的 select 或将 console.log 值移到文本输入的前面,selected 选项将在其中列出并且 boom--正常工作!

请参考这个fiddle:

http://jsfiddle.net/AcfUz/218/

jQuery(document).on('click', '#go', function() {
    console.log("woo");
    var selMulti = jQuery.map(jQuery("#inf_custom_Choosealocation_select :selected"), function(e) {
        return jQuery(e).val();
        console.log("hoo");
    });
    //var selMulti = jQuery("#inf_custom_Choosealocation_select :selected").val();
    console.log(selMulti + "hmm...");
    console.log("hootie");
    //jQuery("#inf_custom_Choosealocation").val(selMulti.join(", "));
    jQuery("#inf_custom_Choosealocation").val(selMulti);
    console.log("who");
});

这在 fiddle 上完美运行,但无论我尝试多少次迭代,它都无法在实时站点上运行。包含所需值的变量始终为空。我这辈子都想不通为什么?????

谁能在我绝望的时刻给我一些启示?已经 7 个小时了,我需要在早上之前解决这个问题。

我想对此进行扩展——fiddle 中的代码是我包含在站点中的代码。表单,然后是结束正文标记之前的脚本。表单是动态加载的(大约需要一秒钟)。我需要完成的是从任何多 select 字段(我从那个开始)中获取用户 selects 的任何值,并将它们作为逗号分隔列表复制到另一个单行文本中输入。 fiddle 工作出色,但我在现场网站上空空如也。我只是 returns blank/empty--it 从来没有给我任何控制台错误(除了丢失的 img),我可以看到我的 console.log 检查点。

这里是直播link:

http://goo.gl/ll1Hz4

尝试将您的代码包装在

jQuery(document).ready(function(){});

您没有在 fiddle 中使用 jQuery 地图,而您的实时代码中有 jquery 地图...

尝试使用您在 fiddle 中的代码更新您的实时站点。

实时代码:(有jQuery地图)

所以,是的,我不确定为什么 :selected 在您的情况下不起作用,但您可以尝试通过选项并手动检查... jQuery("#inf_custom_Choosealocation_select option").each(function(i, o){ console.log(o.selected) })

而不是使用

var selMulti = jQuery.map(jQuery("#inf_custom_Choosealocation_select :selected"), function(e) {
    return jQuery(e).val();
    console.log("hoo");
});

使用

var selMulti=jQuery("#inf_custom_Choosealocation_select").val();

在实时网站上,如果我在控制台中尝试 $("#inf_custom_Choosealocation_select option"),选项会列出两次。使用 $('select') 返回 2 #inf_custom_Choosealocation_select。 (尽管我在页面源代码中没有看到 2 个实例)($("#inf_custom_Choosealocation_select"); returns 一个,但它使用 getElementbyID 并跳过搜索)。也许第二个 select 是由某种叠加层创建的?

总而言之,第二个select的出处我就没有再找了。快速解决方法是使用 select 或搜索属性。以下 select 或在现场测试时工作:

$("select[id=inf_custom_Choosealocation_select] :selected")

但这可能只是暂时的解决方法。您可能也想找到幽灵 select 罪魁祸首 ;)