2017-05-06 16 views
0
tell application "Safari" 
    set theVar to (do JavaScript " 
var a = 
document.getElementById('unitsdiv').getElementsByClassName('even'); 
var b = [] 
for (var i = 0; i < a.length; i++) { 
    b[i] = a[i].textContent; 
}; 
console.log(b.length); \\ Returns 2 
console.log(b[1]);  \\ Returns item 2 of Array 
console.log(b[0]);  \\ Returns item 1 of Array 
b;      \\ Shows both items in Safari Console 
") in document 1 
end tell 

log theVar -- Missing Value 

該代碼在Safari控制檯中按預期工作。我也試着在運行do Javascript命令之前初始化一個列表set theVar to {}無濟於事。任何幫助,將不勝感激。爲什麼我的JavaScript不能將數組返回給AppleScript列表?

這似乎返回值之一

tell application "Safari" 
    tell document 1 
    set theVar to (do JavaScript " 
var a = document.getElementById('unitsdiv').getElementsByClassName('even'); 
var b = []; 
for (var i = 0; i < a.length; i++) 
{ b[i] = a[i].textContent; }; 
console.log(b.length); 
console.log(b[1]); 
console.log(b[0]); 
b[0];") 
end tell 
end tell 
log theVar 

如果我嘗試在javascript代碼的結束使陣列選擇[0]關閉的b然後告訴AppleScript的到log theVar它拋出一個錯誤,那theVar沒有定義。

回答

1

唯一的解決辦法我能想出這並不可怕,萬一別人運行到這個問題

-- Function that allows you to pass a number from applescript to javascript to grab an item of an array. 

on theFunc(theNum) 
    tell application "Safari" 
     tell document 1 
      set a to do JavaScript "var a = 
document.getElementById('unitsdiv').getElementsByClassName('even'); 
var b = [] 
for (var i = 0; i < a.length; i++) { 
    b[i] = a[i].textContent; 
}; 
b[" & theNum & "];" 
     end tell 
    end tell 
-- returns item theNum of the Javascript array 
    return a 
end theFunc 

-- Initialize an array to contain the items returned from the loop below 
set theArray to {} 
-- Initialize a number to increment while the condition is true and pass to the function in the loop below 
set theNum to 0 

-- Use some string that is in each of items of the array, if you don\'t have a specific string, you could try to set it to something like \"does not contain \"missing value\" maybe, or length is something etc 
repeat while theFunc(theNum) contains "LB" 
    set the end of theArray to theFunc(theNum) 
    set theNum to theNum + 1 
end repeat 

-- proof that the variable is an array and contains multiple items 
repeat with a from 1 to the count of theArray 
    log item a of theArray 
end repeat 
+0

愛的解決方案。爲我節省了大量的工作。 –

相關問題