我想拥有许多“infoItem”元素,每个元素都有自己的 jQuery 来管理它们。谁能告诉我为什么当我调用“displayText()”时,该函数中的元素不是包含点击处理程序的元素中的元素,而是页面上的最后一个元素?
<html>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
</div>
<div class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText('ONE');
});
elemMenuTwo.click(function(e) {
that.displayText('TWO');
});
}
this.displayText = function(text) {
elemContent.html('you selected ' + text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>