<table border="0"  class="commentbox">
   <tr>
     <td>
          <div id="comment-f78d0b00-a008-473d-b647-a4a103ee3778"></div>
         <input type="button" class='btnReply' id="reply-f78d0b00-a008-473d-b647-a4a103ee3778" value="Reply"/>

     </td>
 </tr>
</table>

  $(".commentbox .btnReply").live("click", function () {
            //  $(this).hide();
            // i = 1;
            id = $(this).attr("id").split("-")[1]
            alert(id);
            var strDiv =
             "<input type='text' class='txtCmnt' id='txtReply-" + id + "' />
        <input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
            $("#comment-" + id).append(strDiv);


        });


我希望f78d0b00-a008-473d-b647-a4a103ee3778在拆分后发出警告
 f78d0b00

我试图更改ID = comment_ f78d0b00-a008-473d-b647-a4a103ee3778并拆分

id = $(this).attr("id").split("_")[1],but it doesnt work.


已编辑

输入-container-f78d0b00-a008-473d-b647-a4a103ee3778

分割后的输出f78d0b00-a008-473d-b647-a4a103ee3778

最佳答案

一种达到最终结果的复杂方法:

// splits the supplied string by the hyphen '-' character
var string = 'comment-f78d0b00-a008-473d-b647-a4a103ee3778'.split(/-/);
    // removes the zeroeth/first element from the string array
    string.shift();
    // joins the remaining elements from the string back together
var newString = string.join('-');
console.log(newString);​


JS Fiddle demo



编辑以将以上内容转换为功能:

function splitString(haystack, needle){
    if (!needle || !haystack){
        return false;
    }
    var string = haystack.split(needle);
    string.shift();
    return string.join(needle);
}

// the first argument is the string you want to work on,
// the second is the character you want to split on
// f is the variable that will hold the new string
var f = splitString('comment-f78d0b00-a008-473d-b647-a4a103ee3778','-');
console.log(f);​


JS Fiddle demo

参考文献:


join()
shift()
split()

10-06 11:30