首页 > 求一个js全局变量实时改变的思路或者方案。

求一个js全局变量实时改变的思路或者方案。

先上代码!js部分:

$(function(){
        var temp = $("#selectid").children('option:selected').val();
        $('#selectid').change(function(){ 
            var value = $(this).children('option:selected').val();//这就是selected的值 
            changeTemp(value);
        });
        function changeTemp(str){
            temp = str;
            return temp;
        }
        var others = "there are some parameters that didn't bind the select";
        $("#inner").html(others+temp);//只是举个例子,顺便吐槽下自己的烂英语!

下面是html

<select name=""  id="selectid">
        <option value="第一个value">第一个option</option>
        <option value="第二个value">第二个option</option>
        <option value="第三个value">第三个option</option>
    </select>
    <br /><br />
    <div id="inner"></div>

每当执行一次select的change()时,temp能够实时传送到inner里。
受具体业务限制$("#inner").html(others+temp)不能在change()里执行,也不能绑定inner。
求大神提供解决方案!


ecma5有get/set访问器,改写set方法应该可以实现,不过低版本ie不支持ecma5


你的问题不是如何改变全局变量的值,而是如何触发更新dom,正常来说就是change事件触发改变div的内容。不太理解是什么业务限制导致了文档操作不能在change事件执行。
你可以写成一个函数或者自定义事件,放到change里面触发,又或者写一个轮询。


如果不能在 change 事件里写,那就只有定时检查了,定个500 毫秒左右应该没啥感觉的

    setInterval(function() {
        $("#inner").html(others + temp);
    }, 500)

来 jsfiddle 上看结果

http://jsfiddle.net/5zd42kpe/


    <script type="text/javascript" >
    
    
    $(function(){
        var temp = $("#selectid").children('option:selected').val();
        $('#selectid').change(function(){ 
            var value = $(this).children('option:selected').val();
            changeTemp(value);
        });
        function changeTemp(str){
            temp = str;      
     
        var others = "there are some parameters that didn't bind the select";
        $("#inner").html(others+temp); }
        
    });
        </script>



$(function(){
        var temp = $("#selectid").children('option:selected').val();
        $("#inner").html('<span id="innerSpan"></span>');//inner不行,那就换一个可以不
        $('#selectid').change(function(){ 
            var value = $(this).children('option:selected').val();//这就是selected的值 
            var tmp=changeTemp(value);
            $('#innerSpan').html(others+temp);//操作innerSpan不违反要求吧
        });
        function changeTemp(str){
            temp = str;
            return temp;
        }
        var others = "there are some parameters that didn't bind the select";
        $("#innerSpan").html(others+temp);
}
【热门文章】
【热门文章】