简体   繁体   English

如何在Typescript中将对象分配给HTMLElement?

[英]How do you assign an object to an HTMLElement in Typescript?

I keep getting the argument "Argument of type {Object} is not assignable to parameter of type string, with the following code: 我不断收到参数“ {Object}类型的参数不能分配给字符串类型的参数,使用以下代码:

var element = $('<div></div>').addClass('tile')
var tile = {x: 0, y: 0}

element[0].setAttribute('tile', tile)

For some reason Typescript won't allow me to assign the tile property that way. 由于某种原因,Typescript不允许我以这种方式分配tile属性。 Is there's a way that would work? 有一种可行的方法吗? I've also tried element[0].tile = tile, and that causes the error message "property tile does not exist". 我还尝试了element [0] .tile = tile,这会导致错误消息“ property tile不存在”。

The second parameter to setAttribute must be a string. setAttribute的第二个参数必须是字符串。 If you really want to set a JS object as an attribute, you must stringify it: 如果您确实想将JS对象设置为属性,则必须对其进行stringify

element[0].setAttribute('tile', JSON.stringify(tile))

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

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