You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将HTML属性转换为对象

问题原因与解决方法

你的代码生成的不是合法JSON格式,最终解析后得到的其实是字符串而非真正的对象,所以访问属性时会返回undefined。

错误分析

你处理后的字符串是{widget:"fixtures", competition:"1", ...},但JSON规范明确要求:

  • 对象的键必须用双引号包裹
  • 字符串值也必须用双引号包裹(你这部分是对的,但键没加双引号)

后续你用JSON.stringify()把这个非法JSON字符串转成了JSON格式的字符串,再JSON.parse()回来后,得到的还是原来的字符串(比如"{widget:\"fixtures\", ...}"),所以console.log时看起来像对象,但本质是字符串,自然无法通过.访问属性。


正确解法

方法一:手动解析属性字符串(适合简单场景)

const htmlAttribs = 'widget="fixtures" competition="1" season="2020" match="123" template="cell" live="true" sport="hockey"';

// 拆分每个属性键值对,过滤空字符串
const attrPairs = htmlAttribs.split(/\s+/).filter(item => item);
const attrObj = {};

attrPairs.forEach(pair => {
  // 按第一个=拆分键和值
  const [key, valueWithQuotes] = pair.split('=');
  // 去掉值的首尾双引号
  const rawValue = valueWithQuotes.replace(/^"|"$/g, '');
  // 自动转换类型:布尔值、数字、字符串
  attrObj[key] = rawValue === 'true' 
    ? true 
    : rawValue === 'false' 
      ? false 
      : !isNaN(rawValue) 
        ? Number(rawValue) 
        : rawValue;
});

console.log(attrObj);
console.log(attrObj.widget); // 输出 "fixtures"
console.log(attrObj.live); // 输出 true(布尔类型)
console.log(attrObj.competition); // 输出 1(数字类型)

方法二:利用DOM API解析(更可靠,支持复杂属性值)

如果属性值可能包含空格(比如data-title="foo bar"),手动拆分容易出错,用DOM API解析更稳妥:

const htmlAttribs = 'widget="fixtures" competition="1" season="2020" match="123" template="cell" live="true" sport="hockey"';

// 创建临时DOM元素
const tempDiv = document.createElement('div');
tempDiv.innerHTML = `<div ${htmlAttribs}></div>`;
const targetEl = tempDiv.firstElementChild;

const attrObj = {};
// 遍历元素属性
for (const attr of targetEl.attributes) {
  // 同样自动转换类型
  attrObj[attr.name] = attr.value === 'true' 
    ? true 
    : attr.value === 'false' 
      ? false 
      : !isNaN(attr.value) 
        ? Number(attr.value) 
        : attr.value;
}

console.log(attrObj);
console.log(attrObj.season); // 输出 2020(数字类型)

内容的提问来源于stack exchange,提问作者Mohsin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:10:34