如何制作可点击的

时间:2016-12-16 21:17:26

标签: javascript jquery html css asp.net-mvc

我创建了一个表来显示<td>中的SPARQL查询结果,结果显示但是我希望在单击<td>(结果)时显示一个消息框。现在,顶部会显示一个额外的<td>,它仅适用于该特定的一个。单击实际结果<td>时似乎没有任何结果:

我的代码:

    <table id="results">
    <td class="td" onclick="myFunction()"></td>
    </table>
    <body>
        <script type="text/javascript">
         PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>        
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT ?country_name
WHERE {
    ?country rdf:type type:Country108544813.
    ?country rdfs:label ?country_name.

}
                "Limit 1"
                ].join(" ");

                alert("this query: [" + query + "]");

                var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";




</body>

我从在线资料中获取的JavaScript代码仍然让我头脑清醒,它的主要用途是显示查询结果。所以是的答案非常感谢,并感谢阅读:)

2 个答案:

答案 0 :(得分:2)

首先,你的html有点关闭......你的桌子在标签之外,当它应该在里面时:(注意td通常也会在一个之内)

document.onmouseup = function () {
    'use strict';
    document.body.onmousemove = function (e) {
        e.stopPropagation();
    };
document.onmouseup = function () {
    'use strict';
    document.body.onmousemove = function (e) {
        e.preventDefault();
    };
};
document.onmouseup = function () {
    'use strict';
    document.body.onmousemove = function () {
        return;
    };
};

但更准确地说,你的问题是:你已经创建了一个单元格,并且只为它附加了一个onclick事件处理程序。您实际抓取的javascript代码新行和单元格附加到表格中,并且那些没有分配的onclick处理程序。

所以我尝试这样的事情:

<body>
    <table id="results">
        <tr><td class="td" onclick="myFunction()"></td></tr>
    </table>
    <script type="text/javascript">
    ....

&#34;魔法&#34; line是甜蜜的部分:它将处理程序附加在整个表上,但是通过&#34; td&#34;来过滤事件。选择。非常适合动态添加DOM元素...

然后你不需要设置你的初始td,然后你的桌子顶部是空的并且可以点击......相反,只需在你的页面上放一个空表:

<script type="text/javascript">
        var table = $("#results");
        table.on("click", "td", myFunction); // <-- magic!
        var url = "http://dbpedia.org/sparql";

希望这有帮助!

答案 1 :(得分:0)

在查看代码时,您只能在静态

上找到click事件
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>

当你添加动态时,没有类或onclick事件。您可以通过动态地将onclick添加到td或运行一个脚本来解决这个问题,该脚本将该表中的所有tds设置为具有相同的click事件。

function getTableCell(fieldName, rowData) {
            //var td = $("<td></td>");
              var td = $("<td class="td" onclick="myFunction()"></td>");
            var fieldData = rowData[fieldName];
            //alert("fieldName = ["+fieldName +"] rowData[fieldName][value] = ["+rowData[fieldName]["value"] + "]");
            td.html(fieldData["value"]);
            return td;
        }

$("#results td").click(function(){
    var x;
    if (confirm("Press a button!") == true) {
        x = "You pressed OK!";
    } else {
        x = "You pressed Cancel!";
    }
}