我想根据我选择的单选按钮显示图像。首先,我隐藏了所有图像,然后在下一个函数中,我想显示正确的图像。隐藏作品,我在变量值中有正确的值。但是'$(value).show();'不适合我。我已经尝试过编辑它,但没有任何帮助。有人可以帮忙吗?如何正确使用此代码以ID显示img? 感谢
/*when a radio button is clicked, hide imgs*/
$(document).ready(function(){
$(".ClassRadio").click(function(){
$(".ClassImgShape").hide();
});
});
/*shows img based on selected radio button*/
$(document).ready(function(){
$("input:radio[name=radioshape]").click(function() {
var value = $(this).val();
//$("p").text(value);
$(value).show();
});
});
<img class=ClassImgShape id=ushape src="./ushape.png" alt="u-shape" title="u-shape">
<img class=ClassImgShape id=lshape src="./lshape.png" alt="l-shape" title="l-shape">
答案 0 :(得分:1)
请注意,我将完整选择器存储为无线电输入的值,而不仅仅是id,因为jQuery使用它来知道我们正在通过id而不是其他属性进行搜索。此外,您只需要一个 $(document).ready(function(){});
来调用您的代码。
HTML
<input type="radio" name="radio1" value="#image1">
<input type="radio" name="radio2" value="#image2">
<input type="radio" name="radio3" value="#image3">
<input type="radio" name="radio4" value="#image4">
<img class='hide' id='image1' src='foo'/>
<img class='hide' id='image2' src='foo'/>
<img class='hide' id='image3' src='foo'/>
<img class='hide' id='image4' src='foo'/>
的jQuery
//Hide all images with class 'hide' for example
$("img.hide").hide();
//Show on click
$("input[type='radio']").click(function(){
$(this.value).show();
});
答案 1 :(得分:0)
替换它:
$(value).show();
用这个:
$('#' + value).show();
您必须获得的价值,如ushape
或lshape
,但要显示您需要放置#
所需的图片。
<强>更新强>
您也可以这样简单地执行此操作:
$("input:radio[name=radioshape]").click(function () {
$('#' + this.value).show();
console.log(this.value);
// Check the console, if you are getting correct value
// Above line of code needed, just for debugging purpose..
// You can comment that out
});