简体   繁体   English

如何以点表示法引用 HTML object 'name' 属性 - JavaScript

[英]How to reference an HTML object 'name' attribute in dot notation - JavaScript

So, I have a situation where the JavaScript code is creating HTML Elements (in this case it is an <object> ).所以,我遇到了 JavaScript 代码正在创建 HTML 元素的情况(在这种情况下它是一个<object> )。 The name attribute is the only reference that I can use to call for it. name 属性是我可以用来调用它的唯一引用。

To make a long story short, I need to call it to add and remove classList assignments.长话短说,我需要调用它来添加和删除 classList 分配。

Here is my html (yes, I understand the poor practice behind putting <object> s in <ul> s, but this isn't permanent):这是我的 html (是的,我理解将<object> s 放入<ul> s 背后的不良做法,但这不是永久性的):

<div id="wSpace">
            <ul id="fList"></ul>
            <div id="counter"></div>
            <div id="viewer">
            </div>
        </div>

And here's the js... previous to these functions, objects were created, and now there's a list of them floating in <ul id="fList"> :这是 js……在这些函数之前,创建了对象,现在<ul id="fList">中有一个它们的列表:

var list = document.querySelector('ul');
list.addEventListener('click', function (ev) {
    if (ev.target.tagName === 'OBJECT') {
        ev.target.classList.toggle('red');
    }
    if (ev.target.classList.contains('red')) {
        ev.target.setAttribute("name", "c");
    } else {
        ev.target.setAttribute("name", "d");
    }
}, false);

function completed() {
    var t = document.getElementById("completed");
    if (t.value == "True") {
        t.value = "False";
        c.classList.add('green');
    } else if (t.value == "False") {
        t.value = "True";
        c.classList.remove('green');
    }
}

My problem lies in the 'if' statements inside completed() .我的问题在于completed()中的“if”语句。 I'm trying to call <object name="c"> with dot notation (as if you would with an 'id'), but it is not working in the slightest.我试图用点表示法调用<object name="c"> (就像你用'id'一样),但它一点也不工作。 I know there's a million better ways to do this, but this is only an alpha-concept type deal... I just need it running for the sake of demonstrating the idea of the final project.我知道有一百万种更好的方法可以做到这一点,但这只是一个 alpha 概念类型的交易......我只需要它运行以展示最终项目的想法。 I'd appreciate thoughts.我很感激想法。

Object tags are form controls and all form interfaces and APIs apply to them. Object 标签是表单控件, 所有表单接口和 API 都适用于它们。

 const ui = document.forms[0]; const io = ui.elements; const allA = [...io.A]; const b = io.B; allA.forEach(o => o.classList.toggle('red')); b.style.fontSize = '5rem';
 .red { color: red }
 <form> <object name='A'>A</object> <object name='A' class='red'>A</object> <object name='A'>A</object> <object name='B'>B</object> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM