2012-04-14 74 views
1

我正在使用此代码(在.m文件中)将变量传递到捆绑的JavaScript文件中。更改目标中的Javascript变量-C

[animalDesciption stringByEvaluatingJavaScriptFromString:@"var myIDcounterVariable = '1'"]; 

我设置了,它的伟大工程,通过推动一个UIButton改变一个UILabel的价值:

-(IBAction)next:(id)sender { 
number++; 
[currentNumber setText:[NSString stringWithFormat:@"%d", number]]; 

} 

我怎样才能使按钮更改JavaScript变量的值,像我”与标签做什么?

请原谅我的绊脚石!我很新这种编程...

请告诉我,如果我需要给更多的信息。

+0

我在做什么错,为什么我会下降?我非常乐意被告知为什么我不应该问一个问题,或者有更好的方法去做。我花了整整一个下午的时间试图弄清楚如何做到这一点,并发表此评论是最后的手段。 – 2012-04-14 23:48:24

+0

我觉得有点不清楚你确切的问题是什么。您似乎在上面的代码中包含了所有代码,但我不能说出将它们放在一起时出现了什么问题,而且您也没有说明您尝试过的方法。 – 2012-04-15 01:22:14

+0

好吧,基本上我可以通过手动将'1'更改为'2'(或'3'或'4')并重新构建应用程序并运行它来获得第一块代码。 – 2012-04-15 03:15:31

回答

0

我最终什么事做了添加此JavaScript函数来我的UIWebView:

<script type="text/javascript"> 
var max = 100; 

function goToNext() { 
    var hash = String(document.location.hash); 
    if (hash && hash.indexOf(/hl/)) { 
     var newh = Number(hash.replace("#hl","")); 
     (newh > max-1) ? newh = 0 : void(null); 
     document.location.hash = "#hl" + String(newh-1); 
    } else { 
     document.location.hash = "hl1";   
    } 
} 

</script> 

然后用我的IBAction为发送此JavaScript调用是这样的:

- (IBAction)next:(id)sender { 
    [animalDesciption stringByEvaluatingJavaScriptFromString:@"goToNext()"]; 
} 
0

这就是您需要的全部?

-(IBAction)next:(id)sender { 
    number++; 

    // You want Javascript like this to run: 
    //  myIDCounterVariable = '1' 
    // but with the current value of 'number' in it. 

    // Construct the string: 
    NSString* jsString = [NSString stringWithFormat:@"myIDCounterVariable = '%d'", number]; 

    // and run it 
    [animalDesciption stringByEvaluatingJavaScriptFromString:jsString]; 
} 
+0

这看起来正是我想要的,但它对我无能为力!我在想,这可能是因为JavaScript函数需要在页面加载时设置变量,以及稍后变量更改时什么也不做。 – 2012-04-15 03:24:06

+0

听起来似乎合理。你可能希望你的JS有一个像“scrollToAnchorWithIndex()”的函数。然后让Obj-C代码像“scrollToAnchorWithIndex(%d)”一样构造JS字符串并对其进行评估。 – 2012-04-15 03:39:42

+0

是的,这与我所做的相似,我只是用JavaScript进行增量。第二个想法是,Obj-C中的增量可能会更清晰,就像你的建议一样......我会继续发布我的当前配置。 – 2012-04-15 16:45:15