2

I have a snippet of JQuery code that do some bar scrolling.

Since I have three, four, ... n bar to slide into my PHP page, I assign them dinamically an id and pass it to JQuery for be sure that my snippet slide the correct bar on a mouseOver event.

That's the snippet of code that do the "inizialization" of my scrolls

(function($){
 $.fn.horizontalScroll = function(options) {

 var rid = arguments[0];
 var oid = arguments[1];

 var defaults = { };

 var options = $.extend(defaults, options);

 return this.each(function() {

            var horiz_scroll = new dw_scrollObj($(this).attr('id'), $(this).children().attr('id'), $(this).children().children().attr('id'));
            horiz_scroll.setUpScrollbar("dragBar_"+rid+"_offer_"+oid, "track_"+rid+"_offer_"+oid, "h", 1, 1);
            horiz_scroll.setUpScrollControls('scrollbar_'+rid+'_offer_'+oid);

As you can see, "dragBar_"+rid+"_offer_"+oid dinamically concatenates my id(s) to other string part.

That's fine and all goin' well, except when my oid became something like -1

In that case I have an error that says

identifier starts immediately after numeric literal

That's confuse me, because i've read on StackOverflow some questions like this (just a random one) and I expect that behaviour for all concatenation that involves number.

That the snippet of code where all "breaks"

this.timerId = setInterval(this.animString + ".scroll()", 10);

Where this.animString is "dw_scrollObj.col.horiz_container_outer_55_offer_-1" while in other case (where it works) is "dw_scrollObj.col.horiz_container_outer_62_offer_234"

Anyone can explain me why this happen?

4

2 回答 2

7

您正在尝试访问名为dw_scrollObj.col.horiz_container_outer_55_offer_-1. 一些浏览器会让所有元素都可以ID这样访问,但不建议这样做。

它在您的特定情况下不起作用的原因是您编写的不是有效的 javascript 变量名。您访问变量的尝试将被解释为

dw_scrollObj.col.horiz_container_outer_55_offer_ - 1

如果您改为通过以下方式访问您的对象

document.getElementById('dw_scrollObj.col.horiz_container_outer_55_offer_-1')

或者

$('#dw_scrollObj.col.horiz_container_outer_55_offer_-1')

你不会有同样的问题。

对于您的setInterval代码,这意味着

this.timerId = setInterval("$('#" + this.animString + "').scroll()", 10);

或者最好

this.timerId = setInterval(function() {
   $('#' + this.animString).scroll();
}, 10);

如果您的代码处于循环中,并且animString在上下文中会随着时间而改变,您将需要创建一个新的闭包:

this.timerId = setInterval((function(x) {
    return function() {
       $('#'+x).scroll();
    };
})(this.animString), 10);
于 2012-04-18T13:13:59.557 回答
2

您的setInterval代码段中断,因为您传递给的字符串setInterval被评估为 JavaScript。它成为了

dw_scrollObj.col.horiz_container_outer_55_offer_-1.scroll()

但连字符 ( -) 在标识符中无效。

例如,这会引发错误

var some-name = 'foo';
于 2012-04-18T13:13:43.670 回答