.css()不是函数[jQuery]?

KO1*_*O12 8 html javascript jquery angularjs

我有以下自定义标记/指令:

<tile class="ng-scope gridster-item" tilevalue="1" gridster-item="tile" row="0" col = "0" ng-repeat="tile in selectedTiles"> </tile>
Run Code Online (Sandbox Code Playgroud)

我创建了一个键盘控件,其目标是关注selectedTiles array每个键盘事件中的每个tile("tile"指令)(shift + right arrow).

// Keyboard Tile Navigation

        //Starting pos
        var curIndex = -1

        //keyboard control
        $(document).keydown(function(event) {

        if (event.shiftKey && event.which === 39) {
                console.log("right");
                focusNext();
                }
           });

        function focusNext() {
            focusTile(+1);
        }

        function focusTile(delta) {

            var visibleTiles = $scope.selectedTiles;
            var elem = $("[gridster-item='tile']");

            curIndex = curIndex + delta;
            el = elem[curIndex];

        el.attr('tabindex', -1).focus();    
        el.css("border-color", "yellow");

        }
Run Code Online (Sandbox Code Playgroud)

当我得到变量的控制台日志时,elem我得到了dom中出现的tile数组(如预期的那样).问题是当我尝试添加一个.attr()函数或一个.css()函数时,我得到错误说明这些不是函数,我该如何调整?

Dha*_*mar 18

使用$(elem [curIndex])而不是elem [curIndex]并试试这个:

.css()是jquery的方法,如果你想使用那个方法,你可以使用

所以它将是:

$(elem[curIndex]).css("border-color", "yellow");
Run Code Online (Sandbox Code Playgroud)

现在,如果你想使用javascript为元素添加样式,你可以试试这个:

(只是一个例子)

var myElement = document.querySelector("#superman");
myElement.style.backgroundColor = "#D93600";
Run Code Online (Sandbox Code Playgroud)


Bho*_*yar 5

当您使用 like 时elem[curIndex],elem(jQuery 包装器)成为 javascript 对象。所以,你会收到这样的错误,因为它们不是核心 javascript 方法,而是 jquery。

所以,你需要用jquery再次包装它:

$(elem[curIndex])//now using .css() or .attr() will not throw you errors.
Run Code Online (Sandbox Code Playgroud)