Как я могу ссылаться на динамически созданный идентификатор в HTA (vbscript)?

См. Сокращенный код. По сути, я создаю список элементов (принтеров) вместе с динамически созданным уникальным идентификатором переключателя, а затем я хотел бы иметь возможность ссылаться на указанный идентификатор радио, чтобы переключать Проверено между True / False в Sub SetDefaultPrinter. Почему? Потому что использование «Добавить устройства / поиск» слишком сложно для некоторых из наших пользователей, отсюда и симпатичный маленький графический интерфейс. Почему динамический? Потому что у меня несколько отдельных сетей, и я бы предпочел, чтобы сценарий настраивался сам по себе.

<html>
<head>
<title>My HTML application</title>
<HTA:APPLICATION
APPLICATIONNAME="My HTML application"
ID="MyHTMLapplication"
VERSION="1.0"/>
</head>

<script language="VBScript">

Public jj, strPrinters, strModels, strLocations

Sub Window_OnLoad
strPrinters = Array("Printer1", "Printer2")
strModels = Array("HP Color LaserJet 4525", "HP Color LaserJet 4525")
strLocations = Array("Room 1", "Room 2")

jj = UBound(strPrinters)

Call OnClickGo()
End Sub

Sub OnClickGo()
DataArea1.InnerHTML = ""
For i = 0 To jj
        DataArea1.InnerHTML = DataArea1.InnerHTML & "<BR><font style=color:green;font-weight=bold;>" &_
          "<input type=""" & "radio""" & " name=""" &_
          strPrinters(i) & "Radio""" & " id=""" & "Radio" & i & """" &_
          " title=""" & "Clicking here will set " & strPrinters(i) & " as default printer.""" &_
          " onclick=""" & "SetDefaultPrinter(" & i & ")""" & " onmouseover=""" & "Pointer""" &_
          " onmouseout=""" & "DefaultCursor""" & "></input>" &_
          "<span id=""" & strPrinters(i) & "Span""" &_
          " title=""" & "Click here delete printer mapping for " & strPrinters(i) & """" &_
          " onmouseover=""" & "Pointer""" & " onmouseout=""" & "DefaultCursor""" &_
          " onclick=""" & "OnClickDelete(" & i & ")""" &_
          ">" & strPrinters(i) & ", " & strModels(i) & ", Location: " & strLocations(i) & "</span></font>"
Next
End Sub

'========================================
'= Set Default Printer ==================
'========================================
Sub SetDefaultPrinter(ii)
DataArea2.InnerHTML = strPrinters(ii) & " would have been set as default if this was fully functional."
'
' Radio0 and Radio1 are dynamically created IDs, *really* want to somehow
' dynamically reference the dynamically created IDs.
' i.e. something like
'     If ii <> 0 Then (Radio & ii).checked = False
'
If ii <> 0 Then Radio0.checked = False
If ii <> 1 Then Radio1.checked = False
End Sub

'========================================
'= Delete Printer Mapping ===============
'========================================
Sub OnClickDelete(ii)
DataArea2.InnerHTML = strPrinters(ii) & " would have been deleted if this was fully functional."
'Set wshnetwork = CreateObject("WScript.Network")
'wshnetwork.RemovePrinterConnection "\\SERVER\" & strPrinters(PrinterToDelete)
End Sub

'========================================
'= MOUSE Pointers =======================
'========================================
Sub Pointer
document.body.style.cursor = "hand"
End Sub

Sub DefaultCursor
document.body.style.cursor = "default"
End Sub
</script>
<body bgcolor="white">
<span id="DataArea1"></span>
<BR><BR><BR>
<span id="DataArea2"></span>
</body>
</html>

person user2345916    schedule 08.08.2017    source источник


Ответы (1)


user2345916, я изменил ваш код, где переменные передаются так, как вы хотели. Я оставил ваши комментарии нетронутыми, так что вы можете продолжить с того места, где остановились. Надеюсь это поможет!

По сути, ответ на вашу проблему заключается в значениях кнопок «ID», «VALUE» и «ONCLICK».

  • ONCLICK = 'SetDefaultPrinter ("& i &")' передаст зацикленный номер подпрограмме.
  • SetDefaultPrinter (Radioii) устанавливает переменную из поля «ONCLICK» кнопки, которая отправляет вас в эту подпрограмму (в данном случае это 0 или 1).
  • "FileName = document.getElementById (" Radio "& Radioii) .value" получает поле "VALUE" кнопки, которое соответствует полю "ID", установленному между "()", которое в вашем случае также является переменная, полученная из ONCLICK.
  • Отсюда вы можете использовать переменную (FileName), чтобы делать все, что хотите (Match IF / THEN и т. Д.)

    <script language=vbscript>
    Sub Window_OnLoad
    window.resizeTo 500,300
    strPrinters = Array("Printer 1", "Printer 2")
    strModels = Array("HP Color LaserJet 4525", "HP Color LaserJet 4525")
    strLocations = Array("Room 1", "Room 2")
    
    jj = UBound(strPrinters)
    For i = 0 To jj
    strHTML1 = "<span id='Delete" & i & "' value='" & strPrinters(i) & "'title='Click here delete printer mapping for " & strPrinters(i) & "' onmouseover='Pointer' onmouseout='DefaultCursor' onclick='OnClickDelete(" & i & ")'> " & strPrinters(i) & " - " & strModels(i) & ", Location: " & strLocations(i) & "</span>"
    strHTML2 = strHTML2 & "<input type='radio' name='radio' value='" & strPrinters(i) & "' id='Radio" & i & "' title='Clicking here will set " & strPrinters(i) & " as default printer.' onclick='SetDefaultPrinter(" & i & ")' onmouseover='Pointer' onmouseout='DefaultCursor'>" &_
    "" & strHTML1 & "</input><br>"
    
    DataArea1.InnerHTML = strHTML2
    Next
    End Sub
    
    '========================================
    '= Set Default Printer ==================
    '========================================
    Sub SetDefaultPrinter(Radioii)
    FileName = document.getElementById("Radio" & Radioii).value
    DataArea3.InnerHTML = Filename & " would have been set as default if this was fully functional."
    '
    ' Radio0 and Radio1 are dynamically created IDs, *really* want to somehow
    ' dynamically reference the dynamically created IDs.
    ' i.e. something like
    '     If ii <> 0 Then (Radio & ii).checked = False
    '
    If Radioii = 0 Then Radio0 = False
    If Radioii = 1 Then Radio1 = False
    End Sub
    
    '========================================
    '= Delete Printer Mapping ===============
    '========================================
    Sub OnClickDelete(Deleteii)
    RemoveName = document.getElementById("Delete" & Deleteii).value
    DataArea3.InnerHTML = RemoveName & " would have been deleted if this was fully functional."
    'Set wshnetwork = CreateObject("WScript.Network")
    'wshnetwork.RemovePrinterConnection "\\SERVER\" & strPrinters(PrinterToDelete)
    End Sub
    
    '========================================
    '= MOUSE Pointers =======================
    '========================================
    Sub Pointer
    document.body.style.cursor = "hand"
    End Sub
    
    Sub DefaultCursor
    document.body.style.cursor = "default"
    End Sub
    </script>
    




person Mozy    schedule 24.10.2017