簡體   English   中英

javascript:更改 <DIV> onclick值

[英]javascript : changing <DIV> onclick value

我有一個<DIV> ,它被用作這樣的按鈕

<div id='project_1_task_2_is_done' 
class='button_style_1_small' onClick='taskIsDone(1,2,"y");'>
Is done?
</div>

我想在用戶單擊onClick字符串值taskIsDone(1,2,"n")其更改為taskIsDone(1,2,"n") ,然后再次單擊時,將其taskIsDone(1,2,"y")taskIsDone(1,2,"y") ,依此類推。

我正在嘗試通過taskIsDone javascript函數(例如

if(is_done=='n'){
    document.getElementById('project_' + project_id + '_task_' + task_id + '_is_done')
.onclick = "taskIsDone(" + project_id + "," + task_id + ",'y');"
}

但它不起作用。

我在網上查看了7到8個以上的示例,大部分都是從這里(Stackoverflow)開始的,但是我沒有找到問題的答案(基本上是在動態更改該DIV ID的onclick字符串。我不想就像我發現的大多數示例一樣,運行一個函數,只是想更改onclick字符串值,對div按鈕的每次單擊將“ y”修改為“ n”,然后再次將“ y”修改為此類

謝謝!!

參見http://jsfiddle.net/wnw0oskd/

你可以改變它作為一個屬性,作為警報顯示onlick的元素的不是“taskIsDone(1,2,‘Y’);” 但是一個功能。

document.getElementById('project_' + project_id + '_task_' + task_id + '_is_done').setAttribute("onclick", "taskIsDone(" + project_id + "," + task_id + ",'n'");"

如果您打印document.getElementById('your_div').onclick的當前值,您將意識到它不是字符串taskIsDone(1,2,"y"); ,但是:

function (event) {
    taskIsDone(1,2,"y");
}

因此,如果您想更改.onclick的值,請為其分配一個這樣的函數。

示例(在a()b()之間切換.onclick的值):

<html>
    <body>
        <script>
            function a() {
                alert("a()");
                document.getElementById('foo').onclick = function(event) {
                    b();
                }
            }
            function b() {
                alert("b()");
                document.getElementById('foo').onclick = function(event) {
                    a();
                }
            }
        </script>
        <div id="foo" style="position: absolute; left: 20px; top: 20px; width: 200px; height: 50px; background-color: red;" onclick="a();">
        </div>
    </body>
</html>

嘗試這個。

<div id='project_1_task_2_is_done' 
class='button_style_1_small' >
Is done?
</div>

 var check=false;
var button = document.getElementsByClassName('button_style_1_small');
button.click =function(){
      if(check==false){
            check=true;
            taskIsDone(1,2,"n");
        }else{
          check=false;
          taskIsDone(1,2,"y");

          }

      }

要具體回答您的問題,請嘗試將“ onlick”設置為函數而不是字符串:

if (is_done=='n'){
  var elmt = document.getElementById(...); // arguments omitted for brevity
  elmt.onclick = function(project_id, task_id) {
    taskIsDone(project_id, task_id, 'y');
  }
}

話雖這么說,但是有更好的方法可以做這種事情。 例如,您可以將狀態保留在附加到div的data屬性中:

<div id='project_1_task_2_is_done' data-done="no"
   class='button_style_1_small' onClick='toggleDone(ev, 1, 2)'>
   Is done?
</div>
<script type="text/javascript">
function toggleDone(ev, projectId, taskId) {
   var elmt = ev.target
   elmt.dataset.done = elmt.dataset.done == "yes" ? "no" : "yes"
}
</script>

參見http://www.w3schools.com/tags/att_global_data.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM