本人js小白 到公司实习用到js 碰到一个闭包中if语句的问题
花了一天没有解决 求各路高手帮忙
for(var i=0;i<examplenum;i++){
//因为需要动态添加按钮的响应 所以这段代码在一个循环里
//...
var index=i+1;
var text=document.getElementById(id).childNodes[0].childNodes[0].nodeValue;
var audiopathman="temp/"+wordId+"_"+index+"_man.wav";
//...
document.getElementById(man).onclick=function (text,index,audiopathman){
return function(){
var exampleman=
{
//...
'AudioPath':audiopathman
};
//次数加入if语句
//此处调用外壳函数
//alert(call())的结果是正确的 但if语句没有按我的想法执行
if(call()){
alert(1);
//结果alert(1)要么每个都执行 要么每个都不执行
//调用其他函数
}
//////////////
testToSpeech(JSON.stringify(exampleman));
};
}(text,index,audiopathman);
}因为某些关系,隐藏了一部分代码找了很多文章都没有解决问题
或许我的写法不对 不应该这样写 求各路大侠 如果要在闭包的函数中实现那个if语句的功能 根据条件的不同执行不同的语句 应该怎么写闭包的实现已经没有问题 就是if语句不能按我设想的执行
结果alert(1)要么每个都执行 要么每个都不执行求教JavaScript闭包函数
花了一天没有解决 求各路高手帮忙
for(var i=0;i<examplenum;i++){
//因为需要动态添加按钮的响应 所以这段代码在一个循环里
//...
var index=i+1;
var text=document.getElementById(id).childNodes[0].childNodes[0].nodeValue;
var audiopathman="temp/"+wordId+"_"+index+"_man.wav";
//...
document.getElementById(man).onclick=function (text,index,audiopathman){
return function(){
var exampleman=
{
//...
'AudioPath':audiopathman
};
//次数加入if语句
//此处调用外壳函数
//alert(call())的结果是正确的 但if语句没有按我的想法执行
if(call()){
alert(1);
//结果alert(1)要么每个都执行 要么每个都不执行
//调用其他函数
}
//////////////
testToSpeech(JSON.stringify(exampleman));
};
}(text,index,audiopathman);
}因为某些关系,隐藏了一部分代码找了很多文章都没有解决问题
或许我的写法不对 不应该这样写 求各路大侠 如果要在闭包的函数中实现那个if语句的功能 根据条件的不同执行不同的语句 应该怎么写闭包的实现已经没有问题 就是if语句不能按我设想的执行
结果alert(1)要么每个都执行 要么每个都不执行求教JavaScript闭包函数
注释去掉 改成 alert(!!call()) 看一下是不是 都为 true
如果事件调用没问题,应该是你 call有问题
function exampleplay(){
var wordId=document.getElementById("wordid").childNodes[0].nodeValue;
var examplenum=document.getElementById("examplenum").childNodes[0].nodeValue;
for(var i=0;i<examplenum;i++){
//得到各个标签的id
var index=i+1;
var id="example"+index;
var man="exampleman"+index;
var woman="examplewoman"+index;
var text=document.getElementById(id).childNodes[0].childNodes[0].nodeValue;
//去掉中文例句最前面的数字序号和点
var pos=text.indexOf('.');
text=text.substr(pos+1);
var audiopathman="temp/"+wordId+"_"+index+"_man.wav";
var audiopathwoman="temp/"+wordId+"_"+index+"_woman.wav";
//为男声按钮添加事件响应
(function(text,index,audiopathman){
document.getElementById(man).onclick=function (){
var exampleman=
{
'SynthText':text,
'VoiceSpeecher':"henry",
'WordSpeed':"1",
'UseCSSML':"0",
'AudioPath':audiopathman
};
testToSpeech(JSON.stringify(exampleman));
};
})(text,index,audiopathman);
//为女声按钮添加事件响应
(function(text,index,audiopathwoman){
document.getElementById(woman).onclick=function (){
var examplewoman=
{
'SynthText':text,
'VoiceSpeecher':"Catherine",
'WordSpeed':"1",
'UseCSSML':"0",
'AudioPath':audiopathwoman
};
testToSpeech(JSON.stringify(examplewoman));
};
})(text,index,audiopathwoman);
}
}全部代码也就这些 各位看看吧 能不能帮上忙
if语句我去掉了 各位看看怎么加
应该是你 call() 函数有问题
testToSpeech是delphi外壳函数
不是js的
我只能用 不能改
call里用到了audiopathwoman 用alert输出call的结果是对的 但是if就是不对