我无法解决这个问题,我只是开始编写脚本。为了解释,我想使用下面的代码允许用户从列表中选择一个项目。然后,我想将他们选择的内容转换为列表中的数字位置。
例如,如果用户选择了iPod,我希望它将输入保存为2而不是iPod。
以下是我所拥有的:
set productList to {"iPad", "iPod", "iPhone", "Mac", "Apple TV", "Apple Watch", "Beats", "Apple Watch Edition", "Apple Watch Hermes"}
set yourProduct to choose from list of productList with prompt "Select your product: "
on listPosition(this_item, this_list)
repeat with i from 1 to the count of this_list
if item i of this_list is this_item then return i
end repeat
return 0
end listPosition
set item_num to my listPosition(yourProduct, productList)
答案 0 :(得分:1)
当其他答案时,在发布此答案时,确实会返回列表中所选项目的位置,但它们并不考虑使用choose from list
命令可以做出的两种选择以您编码的方式。要修复当前的代码,唯一需要做的就是:
变化:
set yourProduct to choose from list of productList with prompt "Select your product: "
要:
try
set yourProduct to item 1 of (choose from list of productList with prompt "Select your product:")
on error
return
end try
这样做是否会处理用户按下取消 按钮并将yourProduct
的值设置为a string ,而不是列表,如果未按下取消,则从choose from list
命令返回。然后,您的on listPosition(this_item, this_list)
处理程序将在此特定用例中正常运行。
请注意,通常有一种方法可以对某些内容进行编码,但通常最好使用KISS原则,尤其是当首先学习如何编写代码时。
答案 1 :(得分:0)
这适用于我使用最新版本的Sierra。
这会将“位置”存储在变量property theItemPosition
property productList : {"iPad", "iPod", "iPhone", "Mac", "Apple TV", "Apple Watch", "Beats", "Apple Watch Edition", "Apple Watch Hermes"}
property theItemPosition : missing value
set yourProduct to choose from list of productList with prompt "Select your product: "
set yourProduct to yourProduct as string
findPosition(productList, yourProduct)
set theItemPosition to item 1 of result -- returns the chosen product to its position
on findPosition(theList, theListProductChosen)
local theList, theListProductChosen, res
try
if theList's class is not list then error "not a list." number -1704
if {theListProductChosen} is not in theList then return {}
set res to {}
script k
property l : theList
end script
repeat with i from 1 to count of k's l
if k's l's item i is theListProductChosen then set res's end to i
end repeat
return res
on error eMsg number eNum
error "Can't findPosition: " & eMsg number eNum
end try
end findPosition
答案 2 :(得分:0)
你非常接近。你只需要添加一个声明:
set yourProduct to item 1 of yourProduct
set productList to {"iPad", "iPod", "iPhone", "Mac", "Apple TV", "Apple Watch", "Beats", "Apple Watch Edition", "Apple Watch Hermes"}
set yourProduct to choose from list of productList with prompt "Select your product: "
--- ADD This Line to Get Product from Returned List ---
set yourProduct to item 1 of yourProduct
on listPosition(this_item, this_list)
repeat with i from 1 to the count of this_list
if item i of this_list is this_item then return i
end repeat
return 0
end listPosition
set item_num to my listPosition(yourProduct, productList)
choose from list
命令返回所选项目的列表。因此,在进行比较之前,您必须从列表中获取该项目。