2017-08-30 36 views
0

我目前有以下代码来更新URL。我如何将这个结合成更强大的东西,以便我基本上不重复自己3次。我只希望在更改其中一个字段时更新它。你怎么听javascript的多个领域的变化?

$(document).ready(function(){ 
    $('#device_select').change(function() { 
     var device = $(this).val(); 
     var face = $('#face_select').val(); 
     var position = $('#position_select').val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 
    $('#face_select').change(function() { 
     var device = $('#device_select').val(); 
     var face = $(this).val(); 
     var position = $('#position_select').val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 
    $('#position_select').change(function() { 
     var device = $('#device_select').val(); 
     var face = $('#face_select').val(); 
     var position = $(this).val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 
}); 

回答

1

为什么不把你的代码封装在函数中?

function updateURL() { 
    var device = $('#device_select').val(); 
    var face = $('#face_select').val(); 
    var position = $('#position_select').val(); 
    document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
} 

然后你可以打电话给你想要的功能随时随地:

$(document).ready(function(){ 
    $('#device_select').change(updateURL); 
    $('#face_select').change(updateURL); 
    $('#position_select').change(updateURL); 
}); 

更妙的是,你可以添加第二个功能,使你的代码更易读:

function listenForChanges(){ 
    $('#device_select').change(updateURL); 
    $('#face_select').change(updateURL); 
    $('#position_select').change(updateURL); 
} 

并称之为功能上document.ready

$(document).ready(listenForChanges); 
+0

完美为我的scenerio。谢谢! – csling

1

这种方法怎么样?

$(document).ready(function(){ 
     ['#position_select', '#device_select', '#face_select'].forEach(
      function(ev){ 
       $(ev).change(function() { 
        var device = $('#device_select').val(); 
        var face = $('#face_select').val(); 
        var position = $('#position_select').val(); 
        document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
       }); 
      } 
     ) 
    } 
    ) 
4
$('#position_select, #device_select, #face_select').change(function() { 
     var device = $('#device_select').val(); 
     var face = $('#face_select').val(); 
     var position = $('#position_select').val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 

你试过somethign这样吗?