2016-11-21 266 views
0

我是JavaScript和jQuery的新手,我正在开发一款应用程序,目前遇到了麻烦。我有一个对象的属性,我想在click事件上动态更改,特别是切换。jQuery:动态更改对象的属性

示例代码:

var apples = { 
value: "$1.00", 
propertyIwantToChange: red 
}; 

上单击事件触发,物业会变成绿色,然后再次单击它会是红色的。

propertyIwantToChange: greenpropertyIwantToChange: redpropertyIwantToChange: green等等。

我想知道是否有人对此有所了解?任何帮助表示赞赏。

+1

从案例的解决方案,只要你提到'apples.propertyIwantToChange = apples.propertyIwantToChange =='green'? '红':'绿'! –

回答

1

更多使用三元风格的通用功能:

var apples = { 
 
    value: "$1.00", 
 
    propertyIwantToChange: 'green' 
 
}; 
 

 
var toggle = function(obj, prop, first, second) { 
 
    obj[prop] = obj[prop] == first ? second : first; 
 
}; 
 

 
$('input').on('click', function() { 
 
    toggle(apples, 'propertyIwantToChange', 'green', 'red'); 
 
    console.log(apples.propertyIwantToChange); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="button" value="Toggle value" />

1

希望这个片段将

var apples = { 
    value: "$1.00", 
    propertyIwantToChange: 'red' 
    }; 
    function onClickHndler() { 
    // check the property value & change it 
    //using ternary operator 
    apples['propertyIwantToChange'] == 'red' ? 
    apples['propertyIwantToChange'] = 'green' : 
    apples['propertyIwantToChange'] = 'red' 
} 
+0

对于错字感到抱歉。感谢编辑它 – brk

2

您可以创建对象的getter setter方法有用,那么你就可以相应地检查值,并将其更改

var apples = { 
value: "$1.00", 
propertyIwantToChange: 'red', 
getpropertyIwantToChange : function(){return this.propertyIwantToChange}, 
setpropertyIwantToChange : function(val){this.propertyIwantToChange = val} 
} 

随后的onclick检查值并根据需要设定值

if(apples.getpropertyIwantToChange() == 'red'){ 
    apples.setpropertyIwantToChange('green') 
    }else{ 
    apples.setpropertyIwantToChange('red') 
} 
0

你的意思是使用三元运算符这里@Dhaval Marthak说,

apples.propertyIwantToChange = apples.propertyIwantToChange == 'green' ? 'red' : 'green'

您可以在Conditional (ternary) Operator