【问题标题】:Calling jQuery from Within Object从对象内部调用 jQuery
【发布时间】:2017-03-24 19:09:06
【问题描述】:

我正在尝试创建一个计时器来计数,然后在单击按钮时停止。我从here 在线获得了一些我修改过的代码,但是当我尝试调用 jQuery post 方法时出现非法调用错误。我很确定这是一个范围问题,但我不确定解决它的最佳方法。我修改后的代码如下。

var timer={

 init:function(id){
   this[id]={
   obj:document.getElementById(id)
  }
 },

 start:function(id){
    var obj=this[id];
    obj.srt=new Date();
    clearTimeout(obj.to);
    this.tick(id);
    $( "#climbTimer" ).unbind();
    $('#climbTimer').click(function(){timer.finalStop('climbTimer'); return false;});
    
    if ($('#'+id).html().indexOf('Start') != -1)
      $('#'+id).html('Stop Ascend<br><span id="elapsedTime">0.00</span>');
 },

 stop:function(id){
  	clearTimeout(this[id].to);
 },
 
 finalStop:function(id){
	 clearTimeout(this[id].to);
	 
	  $.post('php/climbTime.php', {team: document.getElementById('team').value, roundNum: document.getElementById('round').value, time: document.getElementById('elapsedTime')});
 },

 tick:function(id){
  this.stop(id);
  var obj=this[id],sec=(new Date()-obj.srt)/1000,min=Math.floor(sec/60),sec=sec%60;
  $('#elapsedTime').html(sec>9?sec:''+sec);
  obj.to=setTimeout(function(){ timer.tick(id); },100);
 }
 
	
}

【问题讨论】:

  • 您能否更具体地了解您收到的错误消息?
  • 您需要使用timer.finalStop(id); 而不是timer.finalStop('climbTimer')。最好不要使用已弃用的.unbind(),而是使用.off('click')

标签: javascript jquery scope


【解决方案1】:

几个问题:

  • document.getElementById('elapsedTime') 作为对象属性值传递给$.post:这是一个 DOM 对象,jQuery 将访问其所有属性以尝试对其进行序列化。这将导致错误。相反,您应该获得 textContent 属性:

    $.post('php/climbTime.php', {
        team: document.getElementById('team').value, 
        roundNum: document.getElementById('round').value, 
        time: document.getElementById('elapsedTime').textContent // <---
    });
    
  • 您调用 timer.finalStop('climbTimer'),但这是您的按钮名称,而不是您用来启动计时器的 ID。你需要做的:

    timer.finalStop(id);
    

我还建议使用.off('click') 而不是.unbind(),因为后者自 jQuery 1.7 起已被弃用

最后,如果您正确缩进代码并避免长单行,您可以更好地发现错误。 value 属性在一条长线的最右侧丢失...

【讨论】:

  • 感谢您的帮助。我没有看到缺失值属性,但这实际上让我意识到这不是我想要的值,而是自 elapsedTime 以来的 HTML 内容是一个跨度。
  • 不客气 ;-) 我现在注意到它是在您的代码中生成的跨度。注意:处理文本时最好使用.textContent 而不是.innerHTML,否则您可能会收到不需要的&amp;nbsp;&amp;amp; 之类的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 2019-12-16
  • 2021-12-07
相关资源
最近更新 更多