我可以将 JS 对象或 JS 对象的引用传递给 HTML 标记中的函数吗?
相当菜鸟的问题,我可能认为这个错误,但是...
有没有办法将 javascript 对象(或对它的引用)传递给 HTML 标记中的 javascript 函数?
例如:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
当我检查它时,标记最终看起来像这样:
<div onclick="testThis([object Object])">
附加上下文:
真正的用例是一个搜索页面,我在其中通过 AJAX 查询 SOLR 并以 JS 对象的形式返回结果。当用户单击表示这些搜索结果之一的 HTML 标记时,我希望能够将该对象(或对其的引用)传递给单独的 JS 函数进行处理。
我是否以错误的方式思考这个问题?
Pretty noobish question, and I'm probably thinking about this wrong, but...
Is there a way to pass a javascript object (or a reference to it) to a javascript function within the HTML markup?
For example:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
The markup ends up looking something like this when I inspect it:
<div onclick="testThis([object Object])">
Additional context:
The real use case is a search page in which I am querying SOLR via AJAX and get a result back as JS objects. When the user clicks on the HTML markup representing one of these search results, I want to be able to pass the object(or a reference to it) to a separate JS function for processing.
Am I thinking about this the wrong way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您不能将对对象的引用嵌入到标记中。
相反,您可能想在 Javascript/jQuery 中设置您的点击事件监听:
No, you can't embed a reference to an object into markup.
Instead you probably would like to setup your click event listening in Javascript/jQuery: