Don*_*sto 2 javascript jquery string-concatenation
我有一个JQuery代码片段,可以进行一些条形滚动.
由于我有三个,四个,... n栏可以滑入我的PHP页面,我会将它们分配给一个id并将其传递给JQuery,以确保我的代码片段在mouseOver事件上滑动正确的栏.
这是我的卷轴"inizialization"的代码片段
(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);
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,"dragBar_"+rid+"_offer_"+oid
dinamically将我的id连接到其他字符串部分.
这很好,所有人都很好,除非我oid
变成了类似的东西-1
在那种情况下,我有一个错误说
标识符在数字文字后立即开始
这让我感到困惑,因为我已经在StackOverflow上阅读了一些像这样的问题(只是一个随机的问题)而且我期望所有涉及数字的连接的行为.
所有"打破"的代码片段
this.timerId = setInterval(this.animString + ".scroll()", 10);
Run Code Online (Sandbox Code Playgroud)
哪里this.animString
是"dw_scrollObj.col.horiz_container_outer_55_offer_-1"
而在其他情况下(它的工作原理)是"dw_scrollObj.col.horiz_container_outer_62_offer_234"
有谁能解释我为什么会这样?
您正在尝试访问名为的全局变量dw_scrollObj.col.horiz_container_outer_55_offer_-1
.有些浏览器会使所有元素都可以访问ID
,但不建议这样做.
它在您的特定情况下不起作用的原因是您所编写的内容不是有效的javascript变量名称.您尝试访问变量将被解释为
dw_scrollObj.col.horiz_container_outer_55_offer_ - 1
Run Code Online (Sandbox Code Playgroud)
如果你想改为访问你的对象
document.getElementById('dw_scrollObj.col.horiz_container_outer_55_offer_-1')
Run Code Online (Sandbox Code Playgroud)
要么
$('#dw_scrollObj.col.horiz_container_outer_55_offer_-1')
Run Code Online (Sandbox Code Playgroud)
你不会有同样的问题.
对于您的setInterval
代码,这意味着
this.timerId = setInterval("$('#" + this.animString + "').scroll()", 10);
Run Code Online (Sandbox Code Playgroud)
或者最好
this.timerId = setInterval(function() {
$('#' + this.animString).scroll();
}, 10);
Run Code Online (Sandbox Code Playgroud)
如果您的代码处于循环中,那么animString
随着时间的推移,在上下文中,您将需要创建一个新的闭包:
this.timerId = setInterval((function(x) {
return function() {
$('#'+x).scroll();
};
})(this.animString), 10);
Run Code Online (Sandbox Code Playgroud)