使用此作为第二个变量

问题描述:

我想为$(“。选择器”)使用this.value,$(“#style_background”)是我的保存按钮。当我使用这个代码就像this.value即将'保存',我怎么能做到这个dania,seablue。使用此作为第二个变量

$("#style_background").click(function(){ 

    if ($(".selector").is(":checked")) { 

     document.cookie = "background=" + this.value + ";" + "path=/"; 

    } else {} 

}); 

HTML

<li> 
    <input type="radio" class="selector" id="cookie_dania" name="background" value="dania"> 
</li> 
<li> 
    <input type="radio" class="selector" id="cookie_seablue" name="background" value="seablue"> 
</li> 
+2

*我想用THIS.VALUE为$( “选择 ”)的双选中的值使用$(“ #style_background”)是我保存按钮*不是很清楚 – guradio

+0

“background =”+ this.value即将到来保存我想要获得$(“。selector”)。使用此值 – d3esligner

尝试选择器:checkedeach用于逐个选择选中的单选按钮的值。仅选择了射频按钮。您需要的checkbox代替radio按钮

$("#style_background").click(function() { 
 
    $(".selector:checked").each(function(a){ 
 
// if ($(".selector").is(":checked")) { 
 
    //document.cookie = "background=" + $(this).val() + ";" + "path=/"; 
 
// } else {} 
 
    console.log($(this).val()) 
 
    }) 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<li> 
 
    <input type="checkbox" class="selector" id="cookie_dania" name="background" value="dania"> 
 
</li> 
 
<li> 
 
    <input type="checkbox" class="selector" id="cookie_seablue" name="background" value="seablue"> 
 
</li> 
 
<button id="style_background">save</button>

在你的代码this是指style_background选择,你必须绑定点击事件,所以你需要通过特定的选择为

$("#style_background").click(function(){ 

    if ($(".selector").is(":checked")) { 

     document.cookie = "background=" + $(".selector:checked").val() + ";" + "path=/"; 

    } else {} 

}); 
+0

您只需要获取'checked'选择器的值 –