即使使用“on”,JQuery 也无法识别通过主干视图添加的元素

JQuery not recognising elements added through backbone view even after using 'on'

本文关键字:添加 元素 识别 视图 on JQuery      更新时间:2023-09-26

$(document).ready(function(){
	$('.tagLines').on('mouseover', function(){
		$(this).css("background-color","#ffffff").css("box-shadow", "0 0 4px 4px #C9C9C9");		
	}).on('mouseleave', function(){
		$(this).css('background-color', '#F7F7F7').css("box-shadow", "0 0 2px 2px #C9C9C9");
	}).on('click', function(){
		window.location.hash = "manageMarks";
	});
	
	//this section is for all the views used in the application
		var PGHome = Backbone.View.extend({
			tagName: 'div',
			
			initialize: function(){
				
			},
			
			render: function(){
				var template = _.template($("#home").html(), {} );
				this.$el.html( template );
			}
		});
		
		var pgHome = new PGHome({el: $("#bodyContainer") });	
	//***********************************************************
	//this is a router for the application
		var NavRouter = Backbone.Router.extend({
			routes:{
				"manageMarks": "manage",
				"": "home"
			}
		});
		
		 var navRouter = new NavRouter();
		 navRouter.on('route:manage', function(){
			 console.log("Manage Modules");
		 }).on('route:home', function (){			 
			  pgHome.render();
		 });
		
		Backbone.history.start();	
	//******************************************	
	
});

以上是一个 js 片段,就渲染带有主干的视图而言,它的工作原理是。问题是在渲染视图后,渲染的元素的事件(单击、鼠标悬停、鼠标离开)不会触发。在添加主干之前工作的事件。谁能帮忙?

您需要使用事件委派,因为您在元素附加到页面之前添加事件

$("#bodyContainer").on('mouseover', '.tagLines', function(){
    $(this).css("background-color","#ffffff").css("box-shadow", "0 0 4px 4px #C9C9C9");     
}).on('mouseleave', '.tagLines', function(){
    $(this).css('background-color', '#F7F7F7').css("box-shadow", "0 0 2px 2px #C9C9C9");
}).on('click', '.tagLines', function(){
    window.location.hash = "manageMarks";
});

将事件绑定到 DOM 中没有 .tagLine 元素。

像这样的代码,

var PGHome = Backbone.View.extend({
  tagName: 'div',
  events:{
    'mouseover .tagLines': function(){
        // ...
    },
    'mouseleave .tagLines': function(){
        // ...
    },
    'click .tagLines': function(){
        // ...
    }
  },
  initialize: function(){},
  render: function(){
    var template = _.template($("#home").html(), {} );
    this.$el.html( template );
  }
});