VBScript: How can I dynamically reference an object?
I have an array of object name开发者_StackOverflow中文版s. These objects are HTML elements. I want to loop through this array and change each object's properties dynamically, rather than having to write a list of If Then
or Select Case
statements.
I am looking at GetRef()
which would work for functions, but doesn't seem to work for objects.
I am used to python where I can use getattr()
. PHP's variable variables also work in a pinch. Is there an equivalent in VBScript?
Here's what I would like to be able to do (I know that everything before the comment works -- it's the bit after the comment I need help with):
<table id="softwareStatus">
<tr>
<td><span id="statusProg1">prog1</span></td>
<td><span id="statusProg2">prog2</span></td>
<td><span id="statusProg3">prog3</span></td>
</tr>
</table>
<script language="VBScript">
Dim softwarelist(2,2)
softwarelist(0,0) = "prog1"
softwarelist(0,1) = "statusProg1"
softwarelist(1,0) = "prog2"
softwarelist(1,1) = "statusProg2"
softwarelist(2,0) = "prog3"
softwarelist(2,1) = "statusProg3"
For x = 0 To 2
if IsInstalled(softwarelist(x,0)) Then
' I want to change the object's attributes
' by referring to it dynamically:
softwarelist(x,1).InnerHTML = "<strong>" &_
softwarelist(x,0) & "</strong><br />Installed"
softwarelist(x,1).style.backgroundcolor = "white"
Else
softwarelist(x,1).InnerHTML = "<strong>" &_
softwarelist(x,0) & "</strong><br />Not Installed"
softwarelist(x,1).style.backgroundcolor = "red"
End If
Next
</script>
Edit:
After a few days, I found a solution that works. Since no one has answered my question yet, I answered it myself. I didn't accept my own answer, though, in hopes that someone else will provide a better solution.
I found a better way than my previous answer. It uses a DOM method:
softwarelist = Array("prog1", "prog2", "prog3")
For Each prog in softwarelist
If IsInstalled(prog) Then
Set objItem = Document.GetElementByID("status" & prog)
objItem.InnerHTML = "Text here"
End If
Next
Using a dictionary would also work, oracle certified professional was right about that:
Set dSW = CreateObject("Scripting.Dictionary")
With dSW
.Add "prog1", "divprog1"
.Add "prog2", "spanprog2"
.Add "prog3", "uniqueID3"
End With
For Each prog in dSW
If IsInstalled(prog) Then
Set objItem = Document.GetElementByID(dSW.Item(prog))
objItem.InnerHTML = "Text here"
End If
Next
Both of these methods work well, are clearer and more intuitive, allow more flexibility, and allow for the possibility of more customization. I think they also better use the built-in functionality of both VBScript and HTML. Execute
has its place, but tends to be more of a hack.
I found a way:
For x = 0 To 2
if IsInstalled(softwarelist(x,0)) Then
Execute softwarelist(x,1) & ".InnerHTML = ""Text here"""
End If
Next
It gets sort of unwieldy with more complex strings, but it works, and it's the only thing I could find that works.
精彩评论