每次用户选择其他select
选项时,我都会启动Google分析事件。但是当用户再次点击select
时,会再次触发该事件。我试图在用户选择选项后删除元素事件。我已经尝试了unbind()
和off()
但是没有效果。有人可以帮帮我吗?
JS:
$('#estado').change(function(){
var getEstado = $('#estado option:selected').val();
var getEstadoDesc = $('#estado option:selected').text();
var homeEstado = document.getElementById('estado');
addListener(homeEstado, 'click', function() {
ga('send', 'event', 'Busca', 'Estado', getEstadoDesc);
removeEventHandler(homeEstado, 'click');
});
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
function removeEventHandler(element, type, callback) {
if (element.removeEventListener) element.removeEventListener(type,callback);
else if (element.detachEvent) element.detachEvent('on' + type, callback);
}
$.ajax({
type: 'POST',
data: {estado: getEstado},
url: './ajax/get_cidade.php',
beforeSend: function(data){
},
success: function(data){
$('#load-cursos').html(data);
},
});
});
答案 0 :(得分:0)
我只是对您的代码进行修改,请查看这是否是您想要的。
var selecEvent = function(){
var getEstado = $('#estado option:selected').val();
var getEstadoDesc = $('#estado option:selected').text();
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
function removeListener(element, type, callback) {
if (element.addEventListener) element.removeEventListener(type, callback);
else if (element.attachEvent) element.detachEvent('on' + type, callback);
}
var homeEstado = document.getElementById('estado');
var sendFunction = function() {
alert('Selected ' + getEstadoDesc + ' with value ' + getEstado);
removeListener(homeEstado, 'click', sendFunction);
};
addListener(homeEstado, 'click', sendFunction);
// Stop listen to any changes to prevent multiple ajax call and alerts... etc.
$('#estado').off();
setTimeout(function() {
alert('Select changed');
// Now every thing done. Event sent, content load, we can listen to select again.
$('#estado').change(selecEvent);
}, 3000);
}
$('#estado').change(selecEvent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="estado">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
removeListener或detachEvent,表单文档,需要删除一个函数,所以我必须将执行ga更改为一个简单的警报函数。并将ajax更改为settimeout以模拟ajax延迟。
看看我是否误解了什么?