![](/img/trans.png)
[英]How do you get an HTML element ID to autocomplete in VSCode JavaScript?
[英]How do you get html attributes in a javascript function with a variable element?
當用戶單擊我的HTML中的元素時,我希望在其瀏覽器中顯示一個新選項卡,並將他們單擊的元素的屬性顯示在該窗口中。
這是HTML中的典型元素:
<a id="d0e110" onclick="GetWordFile(this.id)" attr1="attr1_value" attr2="attr2_value" attr3="attr3_value">ElementContent</a>
有很多這樣的元素。 在XLST轉換期間為每個UID生成UID('id =“ {generate-id()}”'')。
這是我當前的javascript函數:
<script>
function GetWordFile(id) {
var opened = window.open("");
opened.document.write();
}
</script>
如果函數的最后一行是“ opened.document.write(id);”,並且單擊了一個元素,則新窗口將為該單擊的元素顯示正確的UID。 因此,連接已成功建立。
但是,我不能使該元素的任何其他屬性出現在新窗口中。 例如,以下函數將產生一個空白的新窗口:
<script>
function GetWordFile(id) {
var opened = window.open("");
opened.document.write(attr1);
}
</script>
嘗試將屬性作為變量獲取也是如此:
<script>
function GetWordFile(id) {
var opened = window.open("");
var a1 = getAttribute("attr1");
opened.document.write(a1);
}
</script>
我還嘗試用內部HTML代替document.write。
誰能確定我做錯了什么以及下一步應該做什么?
您可以將this.attributes
傳遞給函數,不是onclick
.filter()
屬性, .map()
將屬性的.value
傳遞給數組
<script> function GetWordFile(attrs) { attrs = [...attrs].filter(attr => { return attr.name !== "onclick" }).map(attr => attr.value); console.log(attrs); } </script> <a id="d0e110" onclick="GetWordFile(this.attributes)" attr1="attr1_value" attr2="attr2_value" attr3="attr3_value">ElementContent</a>
您需要調用getAttribute()
作為元素的方法,可以使用document.getElementById()
獲得該方法。
function GetWordFile(id) {
var el = document.getElementById(id);
var attr1 = el.getAttribute('attr1');
var opened = window.open("");
opened.document.write(attr1);
}
您可以考慮只傳遞this
,而不是傳遞this.id
作為函數參數。 當您直接提供元素時,為什么要強制該函數搜索元素? 然后該函數將像:
function GetWordFile(el) {
var attr1 = el.getAttribute('attr1');
var opened = window.open("");
opened.document.write(attr1);
}
在加載新窗口時,您正在創建一個新文檔,該文檔不一定知道存在任何其他文檔。 為了使文檔知道存在任何其他文檔,您必須如上所述傳遞所需的信息作為參數。
onclick="someFunction(this)" // which passes in the current scope
// you could then define someFunction like so to get the desired
// result
function someFunction ( htmlObject ) {
attributeList = htmlObject.attributes;
attributeArray = [...attributeList];//now can perform arrayfunctions
let a = "";
for (value in attributeArray) {
a += attributeArray[value].value + " "; // creates a string of
attributes
}
let s = window.open("");
s.document.write(a)}
請注意,您可能要進行一些數組過濾,因為它將返回所有屬性,但一般原理仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.