根据选项元素中的文本进行选项选择

我试图在下拉列表中选择具有传递给函数的文本值,获取它的值,然后选择具有该值的选项的选项。 你能明白为什么这不起作用吗?

function selectAndAddToCart(value) { console.log('The selectAndAddToCart onclick value is ' + value); var optionToSelect = $j('#attribute136').find('option[text="' + value + '"]').val(); //select the option with the node text that equals value //select the option with the node text that equals value var vals = $j('#attribute136').val() || []; vals.push(optionToSelect); $j('#attribute136').val(vals); //initiate add to cart function productAddToCartForm.submit(this); } 

看起来你正在使用noConflict,将$重命名$ $j ,但是在使用$的失败选择器上,而不是$j

我会做 :

 var optionToSelect = $j('option', '#attribute136').filter(function() { return $(this).text().indexOf(value) != -1; }).val(); 

但那只是因为我不太关心contains()选择器:

 $("#attribute136 option:contains(" + value + ")"); 

将值放在引号中。 尝试

 var optionToSelect = $('#attribute136').find('option[text="' + value + '"]').val(); 
 $("#attribute136 option:content("+value")"); 

是你想要的选择器。