简体   繁体   English

代码不在函数内运行

[英]Code doesn't run inside a function

im having a weird problem with my JQuery code. 我的JQuery代码有一个奇怪的问题。 Im trying to change a CSS attribute, to some element on the page. 我试图将CSS属性更改为页面上的某些元素。

this is the code that I tried runing and worked: 这是我尝试运行并工作的代码:

$("#player").css({
    "width" : "+=10"
});

My problem is when I try using this code from a function, it dosnt work. 我的问题是,当我尝试从函数中使用此代码时,它没有起作用。

this is the function: 这是功能:

   function change_elem_size (elemID,whatToChange,value) {
     $('#' + elemID).css({
        whatToChange : value
     });
   }

this is how I call the function: 这就是我所谓的函​​数:

function move_right (elemID,event) {
    $(document).keydown(function(event){
       change_elem_size(elemID,"width","+=10");
       });
}


    $(document).ready(function(){

      move_right("player",event);
    });

Why cant I use a function to change a css attribute? 为什么我不能使用函数来更改CSS属性?

(sorry for my english) (对不起我的英语不好)

Why cant I use a function to change a css attribute? 为什么我不能使用函数来更改CSS属性?

You can. 您可以。 What you can't do is use a dynamic key for an object literal. 不能为对象文字使用动态键。 That means when you do: 这意味着您执行以下操作:

{
    whatToChange : value
}

it treats whatToChange as the name of the property , not as a variable that contains a value that should be the name of the property. 它将whatToChange 视为属性的名称 ,而不是将变量值包含为属性名称的变量。 You'll have to do this: 您必须这样做:

function change_elem_size (elemID,whatToChange,value) {
    var options = {}
    options[whatToChange] = value;
    $('#' + elemID).css(options);
}

The left-hand side of a property initializer inside an object initializer (the bit before the : ) is always a literal, never a variable. 对象初始值设定项( :之前的位)内属性初始值设定项的左侧始终是文字,而不是变量。 So this code: 所以这段代码:

function change_elem_size (elemID,whatToChange,value) {
    $('#' + elemID).css({
        whatToChange : value
    });
}

..sets the property whatToChange , it doesn't use the value of the variable to set a property name. ..set属性whatToChange ,它不使用变量的值来设置属性名称。 To do that, don't use an object: 为此,请不要使用对象:

function change_elem_size (elemID,whatToChange,value) {
   $('#' + elemID).css(whatToChange, value);
}

...or optionally use an object, but use bracketed notation so that the value of whatToChange becomes the property name. ...或选择使用一个对象,但使用方括号表示法,以便whatToChange成为属性名称。 To do that, you have to construct the object first, then add the property to it (you can't do it with an object initializer): 为此,您必须先构造一个对象,然后向其添加属性(您不能使用对象初始化程序来完成它):

function change_elem_size (elemID,whatToChange,value) {
    var change = {};
    change[whatToChange] = value;
    $('#' + elemID).css(change);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM