简体   繁体   English

JQUERY HTML DIV根据标签值隐藏和显示

[英]JQUERY HTML DIV hide and show based on label value

I have a label , that shows dynamic values based on user actions. 我有一个标签,该标签显示基于用户操作的动态值。 For example 1 or 2. I would like to show div element with id="charts_div" if the label value is "1" I would like to hide div element, if the value is "2" This example is simplified as possible, so I could get basic idea where i am stuck 例如1或2。如果标签值为“ 1”,我想显示id =“ charts_div”的div元素。如果值为“ 2”,我想隐藏div元素。我可以基本了解我被困在哪里

HTML 的HTML

<label id="label"></label>
 <div id="chart1_div" style="width:100%; height:200px"></div>
 <div id="chart2_div" style="width:100%; height:200px"></div>

JQUERY JQUERY

$(document).ready( function() {
$('#label').bind('change', function (e) { 
if ($('#label').text() == "1")
{
$('#chart1_div').show();
$('#chart2_div').hide();

}
else if $('#label').text()=="2")
{
  $('#chart1_div').hide();
  $('#chart2_div').show();
}         
}).trigger('change');
});

You can't bind change event to an element that doesn't have that kind of event. 您不能将change事件绑定到没有这种事件的元素。 Put this change logic inside the event that is actually doing the changing of the label 's text. 将此更改逻辑放入实际上正在更改label文本的事件中。

As it was said, you can't bind a change event to a label . 如前所述,您不能将change事件绑定到label Make whatever is changing your label also change the divs being shown. 进行任何更改标签的操作也会更改所显示的div。 Supposing it's a button, do something like this: 假设它是一个按钮,请执行以下操作:

HTML 的HTML

<label id="myLabel">1</label>
<button id ="myButton">Toggle between 1 and 2</button>
<div id="chart1_div" style="width:100%; height:200px">a</div>
<div id="chart2_div" style="width:100%; height:200px">b</div>

JS JS

$(document).ready( function() {
    $("#myButton").click(function(){
        if ($('#myLabel').text() == '1')
        {
            $("#myLabel").text('2');
            $('#chart1_div').show();
            $('#chart2_div').hide();
        } else if ( $('#myLabel').text()=='2')
        {
            $("#myLabel").text('1');
            $('#chart1_div').hide();
            $('#chart2_div').show();
        }        
    });
});

Check out a live example on this jsfiddle ;) 在此jsfiddle上查看一个实时示例;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM