2011-10-21 42 views
9

我想在jQuery中做一些棘手的事情(至少對我來說)。我有一個綁定到一個函數調用add_course,看起來像這樣一個複選框:jquery以編程方式點擊新的DOM元素

function add_course(){ 
     var id = $(this).attr('id'); 
     if ($(this).is(':checked')){ 

      if($('#courseInput').val().search(id) < 0){ 
       $('#CourseSummary').append('<span id="cn'+id+'"><a href="#" class="courseDel" id="'+id+'">X</a> '+$('#course'+id+' a').html()+'<br/></span>'); 
       $('#courseInput').val(function(index,value){ 
        return value+ id +',1;'; 
       }); 
       addTotal($('#price'+id).text()); 
      } 
      imageSync(); 
     }else{ 
      //This is where my question refers to. 
      $('a#'+id+'.courseDel').click(); 
     } 
    } 

當有人檢查複選框,一些數據和鏈接跨度上被添加到頁面。新鏈接連接到不同的功能

$('.courseDel').live('click', del_course); 

del_course做了一大堆東西,就像add_course一樣。

正如你可以在add_course函數中看到的那樣。我檢查這個複選框是否已經被選中,只有在已經被選中的情況下才執行。

這裏是del_course:

 function del_course(){ 
     var id = $(this).attr('id'); 
     $('#cn'+id).remove(); 
     $('#courseInput').val(function(index,value){ 
      return value.replace(id+',1;',""); 
     }); 
     subtractTotal($('#price'+id).text()); 
     imageSync(); 
    } 

我想有我add_course功能的其他部分觸發時複選框被選中的是得到了附加的相應鏈接del_course。這不起作用。我可能過於複雜的東西。

這裏是複選框的HTML(其中一人爲例):

<input type="checkbox" class="courseAdd" name="courseAdd" id="204"/> 

這裏是該被添加的鏈接的HTML當有人點擊複選框:

<span id="cn204"><a href="#" class="courseDel" id="204">X</a> Course Title<br/></span> 

當有人點擊鏈接時它工作得很好,但是如何以編程方式觸發它?

+0

2項這裏要注意:第一,'id'應該是唯一的,不能共享像你擁有了它,也'ID和名稱標記必須以字母開頭([A-ZA-Z]),並可能([0-9]),連字符(「 - 」),下劃線(「_」),冒號(「:」)和句點(「。」)。 /www.w3.org/TR/html4/types.html此外,重讀後http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html –

+0

這個問題我不確定我是否理解 - 你遇到的問題是什麼?//這是我的問題所指的地方。 $('a#'+ id +'。courseDel')。click(); – jbabey

回答

7

既然你已經創建的元素的ID,只需refernce的ID,並使用trigger()方法:

​​

此外,一個ID,這只是一個數字是不正確的:

ID和名稱標記必須以字母開頭([A-ZA-Z]),並且可以是 後跟任意數量的字母,數字([0-9]),連字符( 「 - 」), 下劃線(「_」),冒號s(「:」)和句點(「。」)。

+0

更不用說他有多個具有相同ID值的元素 –

+0

問題在於我的命名規則。 – lovefaithswing

1

使用jquery的trigger()函數。

$('.courseDel').trigger('click'); 
+0

這將觸發'courseDel'類的所有錨的點擊事件。我相信OP想要觸發剛剛添加的錨的點擊事件。 –

0

從長遠來看,它可能有助於重新組織代碼,以便從應用程序邏輯中分離DOM事件處理。

//Functions to add and remove stuff (these are *not* event handlers) 
//Since they now receive explicit parameters 
// you have full power over when to add and remove stuff and functions 
// can very easily call eachother if needed. 

//You can have any kind of state you might need, without having to 
//trick the dom into storing it for you: 
var currentlySelectedCourse = null; 

function add_course(id){ 
    //its now easy to access global state like the 
    //currently open course 
    //and it is now easy to call other functions like del_course 
} 

function del_course(id){ 
} 

//event handling can now become just a simple layer... 

$('.courseDel').live('click', function(){ 
    var id = //get the id or what parameters you need 
    del_course(id); //pass it to the backend function 
}); 
相關問題