我有一个按钮,其中它是 asp.net webforms 中的旧应用程序,因此这些生成的 id 是我必须使用的:
<input type="button" onclick="setDateTimeOn(this);" name="GridView1:_ctl2:AddButton0" value="On" id="GridView1__ctl2_AddButton0" class="btn-blue">
<input name="GridView1:_ctl2:txtStormTimeOn" type="text" id="GridView1__ctl2_txtStormTimeOn">
我有一个我调用的函数
function setDateTimeOn(x){
//alert(x.id);
console.log(x.id);
//$('#x.id').val(
//NEED TO SET textbox to date and time in this format --> 09-11-2015 10:03
}
我需要使用jquery或javascript来查找“ctl2”,从而真正解析以查找“_ctl2_AddButton0”之前和“GridView1__”之后的字符
我过去使用过一些带有正则表达式的 jquery 代码,其中我会使用“^”和部分名称,但在这种情况下,我知道格式始终是
GridView1__VALUEIWANT_txtStormTimeOn
然后我知道如何用该值填充我的文本框(有很多行都是使用 asp.net Web 表单预先生成的 gridview,我无法在此应用程序中更改它。
编辑/更新
到目前为止,这更接近
function setDateTimeOn(x){
console.log(x.id); // shows GridView1__ctl2_AddButton0
var re = /__(.+)_/;
// your control name was used an as example:
//var str = 'GridView1__ctl2_AddButton0';
var str = x.id;
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// m[0] == 'ctl2'
console.log(m[0]); // shows __ctl2_
}
编辑2:
<table>
<tr>
<td style="width:5px;">
<input type="button" name="GridView1:_ctl2:AddButton0" value="On" id="GridView1__ctl2_AddButton0" class="btn-blue">
</td>
<td style="width:150px;">
<input name="GridView1:_ctl2:txtStormTimeOn" type="text" value="asdfasdf" id="GridView1__ctl2_txtStormTimeOn">
</td>
</tr>
</table>
最佳答案
试试这个
function setDateTimeOn(elm) {
var formattedDate = GetCurrentDateTime(); //get formatted date
$(elm) //clicked button
.parent("td") // container td
.next() // next td
.find("input") // find child input
.val(formattedDate); //set date
}
function GetCurrentDateTime() {
var now = new Date(),
hours = now.getHours(),
ampm = hours < 12 ? "AM" : "PM";
hours = (hours % 12 ) || 12;
return (now.getMonth() + 1) + "-"
+ now.getDate() + "-"
+ now.getFullYear() + " "
+ hours + ":"
+ pad(now.getMinutes()) + " "
+ ampm;
}
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
无需省略onclick="setDateTimeOn(this);"
。
关于javascript - asp.net使用jquery和javascript来确定与按钮匹配的文本框ID的中间部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32529413/