繁体   English   中英

Javascript事件监听器-由Javascript设置的“更改”值

[英]Javascript Event Listener - “change” value set by Javascript

我有一个旨在将用户输入的连接起来的单独地址字段更改为单个隐藏字段的过程,供Google地图用来在该位置上放置图钉。

负责串联的事件侦听器正常运行,但是当我尝试将侦听器链接到隐藏字段以执行引脚放置时,该功能未执行。

这是我正在使用的代码:

$(document).ready(function initMap() {

    ...

    function join_address() {
        var address = document.getElementById('id_form5-address1').value;
        var city = document.getElementById('id_form5-city').value;
        var state = document.getElementById('id_form5-state').value;
        var zip = document.getElementById('id_form5-zip').value;
        document.getElementById('id_jointAddress').value = address+", "+city+", "+state+", "+zip;
        }

    document.getElementById("id_form5-city").addEventListener("change", join_address);
    document.getElementById("id_form5-state").addEventListener("change", join_address);
    document.getElementById("id_form5-zip").addEventListener("change", join_address);

    function codeAddress() {
        console.log("function engaged")
        var address = document.getElementById("id_jointAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }

    document.getElementById("id_jointAddress").addEventListener("change", codeAddress);

    ...

}

“启用功能”甚至不会打印到控制台,因此我假设构造错误的侦听器或放置在错误的位置。 有人可以协助吗?

编辑:这是有问题的html对象:

<input type="hidden" name="jointAddress" id="id_jointAddress">

如果我取消隐藏该元素,然后直接在字段中键入,它将触发侦听器。 我认为“更改”侦听器无法响应通过JavaScript进行的更改。 有人知道适合我的解决方案吗?

问题在于,以编程方式设置value不会触发更改事件。 您可以自行发起综合事件 参见http://jsfiddle.net/mendesjuan/uct8bL9d/2/

如果您使用我链接到fireEvent函数 ,则只需在代码中添加以下行

var joint = document.getElementById('id_jointAddress');   
joint.value = address + ", " + city + ", " + state + ", " + zip;
fireEvent(joint, 'change');

这是减少问题的方法:

 document.querySelector('input').addEventListener('change', function() { document.getElementById('output').innerHTML +='changed <br />'; }); document.querySelector('button').addEventListener('click', function() { var input = document.querySelector('input'); input.value = new Date(); fireEvent(input, 'change') }); /** * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically * by testing for a 'synthetic=true' property on the event object * @param {HTMLNode} node The node to fire the event handler on. * @param {String} eventName The name of the event without the "on" (eg, "focus") */ function fireEvent(node, eventName) { // Make sure we use the ownerDocument from the provided node to avoid cross-window problems var doc; if (node.ownerDocument) { doc = node.ownerDocument; } else if (node.nodeType == 9){ // the node may be the document itself, nodeType 9 = DOCUMENT_NODE doc = node; } else { throw new Error("Invalid node passed to fireEvent: " + node.id); } if (node.dispatchEvent) { // Gecko-style approach (now the standard) takes more work var eventClass = ""; // Different events have different event classes. // If this switch statement can't map an eventName to an eventClass, // the event firing is going to fail. switch (eventName) { case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead. case "mousedown": case "mouseup": eventClass = "MouseEvents"; break; case "focus": case "change": case "blur": case "select": eventClass = "HTMLEvents"; break; default: throw "fireEvent: Couldn't find an event class for event '" + eventName + "'."; break; } var event = doc.createEvent(eventClass); var bubbles = eventName == "change" ? false : true; event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable. event.synthetic = true; // allow detection of synthetic events // The second parameter says go ahead with the default action node.dispatchEvent(event, true); } else if (node.fireEvent) { // IE-old school style var event = doc.createEventObject(); event.synthetic = true; // allow detection of synthetic events node.fireEvent("on" + eventName, event); } }; 
 <input /> <button>Set programatically</button> <div id="output"> </div> 

问题在于,以编程方式设置值不会触发更改处理程序。 如果使用jQuery并调用val() ,它将触发综合更改事件。 尝试更新您的JavaScript以使用jQuery。

$(function(){
    function initMap() {
        ...
    }

    function join_address() {
        var address = $('#id_form5-address1').val();
        var city = $('#id_form5-city').val();
        var state = $('#id_form5-state').val();
        var zip = $('#id_form5-zip').val();
        $('#id_jointAddress').val(address+", "+city+", "+state+", "+zip);
    }

    $("#id_form5-city").on("change", join_address);
    $("#id_form5-state").on("change", join_address);
    $("#id_form5-zip").on("change", join_address);

    function codeAddress() {
        console.log("function engaged")
        var address = $("#id_jointAddress").val();
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }

    $("#id_jointAddress").on("change", codeAddress);
});

暂无
暂无

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

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