2009-09-11 32 views
6

我一直在思考/搜索下面存在的問題的等價物,並且找不到任何東西。 有沒有一種方法可以重寫這個以使用jQuery作爲替代方法?將「document.getElementById」轉換爲jQuery

上半部分代碼。

<a href="link.php?test=true" onclick="request(this)" target="_blank"> 

<a id="step2" href="javascript:alert('NOT FINISHED!');"> 

下半年的代碼。

<script language="javascript"> 
var requests = 16; 

function request(self) 
{if(self.href != "#") 
requests -= 1; 

self.childNodes[0].src = "images/clear.gif"; 

if(requests === 0) 
document.getElementById("step2").href = "next.php";} 
</script> 

而我想做一個jQuery var請求類型的東西。我想onclick="request(this)與我的jQuery一起工作。

+1

更改href很容易,但我不知道你真的想做什麼。也許你想要完成什麼的解釋會有所幫助。僅僅改變href就像一個動作一樣毫無意義。 – tvanfosson 2009-09-12 00:06:02

+0

我有5個按鈕,並且我希望它每次按下按鈕時都會請求它,以便在滿足請求後,它將更改「id(about)」的href。目前href =「#」允許他們不繼續,這麼說呢? – Homework 2009-09-12 00:08:21

回答

10

的回答你的問題(標題)是替代

document.getElementById('about').href = '#'; 

$('#about').attr('href','#'); 

我不知道這是否實際上h儘管如此,我仍然不知道你在做什麼。根據你的評論和代碼示例,看起來你正在嘗試做某種嚮導,但是我不知道如何根據你發佈的內容實際工作。

更新:

也許是這樣的:

<a href="link.php?test=true" onclick="request(this)" target="_blank" class='request'></a> 

<a id="step2" href="next.php">Step 2</a> 

<script language="javascript"> 
    $(function() { 
     var requests = 16; 
     $('#step2').click(function() { 
      alert('Not finished'); 
      return false; 
     }); 
     $('.request').click(function() { 
      var $this = $(this); // save jQuery reference to element clicked 

      // swap indicator image source 
      $this.find('img:first').attr('src','images/clear.gif'); 

      // if the number of flipped indicators equals the number of requests 
      // remove the click handler from the step 2 link 
      // this removes the alert and allows the user to proceed 
      if ($('.request img[src="images/clear.gif"]').length == requests) { 
       $('#step2').unbind('click'); 
      } 

      ...do something with the href for this request via ajax??? 

      // replace this handler with one that simply returns false 
      // and remove the href since we're done with this request 
      $(this).unbind('click').attr('href','#').click(function() { return false; }); 

      // stop the default action for the request 
      return false; 
    }); 
</script> 
2

是否這樣?我認爲我失蹤/不理解某事雖然...

$('#about').click(function(evt) { 
    request(this); 
}); 
0

This?不知道我完全得到你想要的

function request(element) 
{ 
    $(element).doSomething(); 
    return false; 
} 

援引什麼:

onclicked="return request(this);" 
+0

要求?它是什麼?鏈接頁面? – tvanfosson 2009-09-12 00:03:58

+0

爲什麼不只是完全刪除錨標籤,所以他們甚至不能點擊它? – tvanfosson 2009-09-12 00:11:01

2

爲了方便,你可以在$對象上定義一個額外的方法

$.getElementById = function(id){ 
    return $('#'+id).get(0); 
}; 

然後你可以只改變所有從您的通話

document.getElementById 

$.getElementById 

有噸這一警告的,但它可以根據您的情況是有用的。

+0

你能否提供一些關於警告的提示 – nus 2012-08-03 23:21:06