簡體   English   中英

jQuery-防止onclick和檢索函數調用的參數

[英]jquery - Prevent onclick and retrieve parameters of function call

我們被要求對某些代碼進行創可貼措施,因此這看起來確實很愚蠢,但請耐心等待。

我們需要防止錨的onclick方法,並檢索要進行的函數調用的參數,以便使用這些參數調用其他函數。 這是到目前為止的代碼和html:

<p><a href="#" onclick="openMoreProductVideos('Title of video','VideoCode','false');return false;"><span class="txt">View all videos</span></a></p>

JS:

// undefine onclick so it is not handled with broken function
$('a[onClick^=openMoreProductVideos]').each(function () {
    this.onclick = undefined;   
});

    // grab parameters from onclick function call and submit to new function.
$('a[onClick^=openMoreProductVideos]').click(function () {
    strStart = "openMoreProductVideos(";
    strFinish = ");return false"
    srctext = $(this).parent().html();      
    var re = strStart + ".*?"+strFinish
    var newtext = srctext.match(re)[1];
    var callparams = newtext.substring(1,newtext.length-1);
    testparams(callparams);
  });

 // test function to see if parameters are working
 function testparams (a,b,c){
    console.log (a,b,c)
 }

問題在於返回的字符串(callparams)被視為一個參數。 我不是正則表達式專家,所以我希望有一個比我更能快速看到解決方案的經驗的人。

非常感謝。

如果callparams是一個字符串,例如"'Title of video','VideoCode','false'"則嘗試

testparams(callparams.split(',')); 
   /* transforming string into an array 
    * ["'Title of video'", "'VideoCode'", "'false'"] 
    */
...

function testparams (pars){
   console.log (pars[0], pars[1], pars[2]);
   /* if necessary remove trailing quotes with .replace() method */
}

暫無
暫無

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

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