【问题标题】:Android: Pass html string from java to javascriptAndroid:将html字符串从java传递给javascript
【发布时间】:2014-07-10 15:25:58
【问题描述】:

我正在构建一个 android 应用程序,我有一个基于 web 服务器的 php 页面,它返回类似的数据

{"categories":[{"id":123,"name":"Category 1","img":""},{"id":12,"name":"Category 2","img":""},{"id":56,"name":"Category 2","img":""}]}

现在我已经设法在 java 中使用这些数据并获取我需要的每个元素。我已经阅读了一个模板文件,其中包含如下代码:

<a class=button id="category_id"><img src="img_path"></img>category_name</a>

在 Java 中,我在这个模板的内容上做 string.replace

content += template.replace("category_id", id).replace("category_name", name).replace("img_path", img_path);

这是在每个类别的 for 循环中完成的,现在是一个值字符串:

<a class=button id="123"><img src=""></img>Category 1</a><a class=button id="12"><img src=""></img>Category 2</a><a class=button id="56"><img src=""></img>Category 3</a>

现在这个字符串在 javascript 中调用时像:

function showAndroidCategories() {
            var html = Android.showCategories();
            document.getElementById('.button-layout').innerHTML = html;
        }

.button-layout 是我 webView 上的一个 div。 但是我收到此错误:

"Uncaught TypeError: Cannot set property 'innerHTML' of null", source: file:///android_asset/www/index.html (32)

它指的是你可以在上面看到的我的 javascript 的最后一行。 我要做的就是从数据中加载一个类别列表并为每个类别创建一个按钮。

谢谢。乔什。

【问题讨论】:

    标签: javascript java android html


    【解决方案1】:

    您将 button-layout 用作类名 (.) 而不是 ID (#)。

    function showAndroidCategories() {
         var html = Android.showCategories();
         document.getElementById('button-layout').innerHTML = html;
    }
    

    也许这就是你要写的。

    【讨论】:

    • 绝妙的地方,我不敢相信阻止我的代码工作的唯一因素是'。' :/我已经接受了你的回答,但我不能投票给你,直到我似乎有更多的声誉。
    • 别担心。很高兴有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 2017-09-28
    • 2015-05-23
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多