programing

jQuery가 ID에 .(주기)가 있는 요소를 선택하도록 하려면 어떻게 해야 합니까?

starjava 2023. 10. 29. 18:56
반응형

jQuery가 ID에 .(주기)가 있는 요소를 선택하도록 하려면 어떻게 해야 합니까?

다음 클래스와 컨트롤러 작업 방법이 주어집니다.

public School
{
  public Int32 ID { get; set; }
  publig String Name { get; set; }
  public Address Address { get; set; }
}

public class Address
{
  public string Street1 { get; set; }
  public string City { get; set; }
  public String ZipCode { get; set; }
  public String State { get; set; }
  public String Country { get; set; }
}

[Authorize(Roles = "SchoolEditor")]
[AcceptVerbs(HttpVerbs.Post)]
public SchoolResponse Edit(Int32 id, FormCollection form)
{
  School school = GetSchoolFromRepository(id);

  UpdateModel(school, form);

  return new SchoolResponse() { School = school };
}

그리고 다음과 같은 형태:

<form method="post">
  School: <%= Html.TextBox("Name") %><br />
  Street: <%= Html.TextBox("Address.Street") %><br />
  City:  <%= Html.TextBox("Address.City") %><br />
  Zip Code: <%= Html.TextBox("Address.ZipCode") %><br />
  Sate: <select id="Address.State"></select><br />
  Country: <select id="Address.Country"></select><br />
</form>

학교 인스턴스와 학교 주소 구성원 모두 업데이트 할 수 있습니다.이거 꽤 좋네요!ASP 감사합니다.NET MVC팀!

그러나 jQuery를 사용하여 드롭다운 목록을 선택하면 사전에 작성할 수 있습니까?저는 제가 이 서버 쪽을 할 수 있다는 것을 깨달았지만, 페이지에는 목록에 영향을 미치는 다른 동적인 요소들이 있을 것입니다.

제가 지금까지 가지고 있는 것은 다음과 같고, 셀렉터가 ID와 일치하지 않는 것 같아 작동하지 않습니다.

$(function() {
  $.getJSON("/Location/GetCountryList", null, function(data) {
    $("#Address.Country").fillSelect(data);
  });
  $("#Address.Country").change(function() {
    $.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
      $("#Address.State").fillSelect(data);
    });
  });
});

Google 그룹에서:

각 특수 문자 앞에 백슬래시 두 개를 사용합니다.

jQuery 셀렉터의 백슬래시는 다음 문자를 비웁니다.그러나 백슬래시는 자바스크립트 문자열의 이스케이프 문자이기도 하기 때문에 두 개가 필요합니다.첫 번째 백슬래시는 두 번째 백슬래시를 탈출하여 문자열에 있는 실제 백슬래시를 하나 제공합니다. 그러면 jQuery의 다음 문자를 탈출합니다.

그래서, 당신이 보고 있는 것은

$(function() {
  $.getJSON("/Location/GetCountryList", null, function(data) {
    $("#Address\\.Country").fillSelect(data);
  });
  $("#Address\\.Country").change(function() {
    $.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
      $("#Address\\.State").fillSelect(data);
    });
  });
});

또한 CSS 표기에 사용되는 문자가 있는 ID로 요소를 선택하려면 어떻게 해야 합니까?jQuery FAQ 에서 확인할 수 있습니다.

ID에 공백이 있으면 jQuery id selector를 사용할 수 없습니다.속성 선택기 사용:

$('[id=foo bar]').show();

가능한 경우 요소 유형도 지정합니다.

$('div[id=foo bar]').show();

Jquery를 위해 탈출하기:

function escapeSelector(s){
    return s.replace( /(:|\.|\[|\])/g, "\\$1" );
}

사용 예:

e.find('option[value='+escapeSelector(val)+']')

자세한 정보는 여기에.

ASP의 릴리스 후보.방금 출시된 NET MVC가 이 문제를 해결했습니다. 이제 ID 속성에 대한 밑줄로 점을 바꿉니다.

<%= Html.TextBox("Person.FirstName") %>

렌더링 대상

<input type="text" name="Person.FirstName" id="Person_FirstName" />

자세한 내용은 14페이지부터 시작하는 릴리스 노트를 참조하십시오.

이 문서는 jQuery Selectors 문서에 나와 있습니다.

메타 문자(예:!"#$%&'()*+,./:;<=>?@[\]^`{|}~이름의 문자 그대로 부분으로, 두 개의 백슬래시를 사용하여 탈출해야 합니다.\\. 예를 들어, 다음과 같은 요소가 있습니다.id="foo.bar", 셀렉터를 사용할 수 있습니다.$("#foo\\.bar").

간단히 말해서, 접두사를 붙입니다..와 함께\\다음과 같이

$("#Address\\.Country")

왜 안해요?.신분증에 근무하나요?

문제는..특별한 의미가 있습니다. 다음 문자열은 클래스 선택으로 해석됩니다. 그래서$('#Address.Country')일치할 것입니다<div id="Address" class="Country">.

다음과 같이 탈출한 경우\\., 원하는 ID와 일치하는 특별한 의미가 없는 일반 텍스트로 처리됩니다.<div id="Address.Country">.

이것은 모든 캐릭터에 적용됩니다.!"#$%&'()*+,./:;<=>?@[\]^`{|}~그렇지 않으면 jQuery에서 선택자로서 특별한 의미를 가질 수 있습니다.그냥 붙이기\\정상적인 텍스트로 취급할 수 있습니다.

2인 이유\\?

bdukes의 답변에 언급된 것처럼, 우리가 2개가 필요한 이유가 있습니다.\성격.\자바스크립트에서 다음 문자를 벗어날 것입니다.자바스크립트가 문자열을 해석하는 경우"#Address\.Country", 그것은 볼 것입니다.\, 다음 문자를 쓰레기로 가져다가 문자열이 전달되면 제거한다는 의미로 해석합니다.$() jQuery는 을 , jQuery로 볼 수 ."#Address.Country".

거기서 두번째가\경기하러 들어옵니다.첫 번째 것은 자바스크립트가 두 번째 것을 리터럴(특별하지 않은) 문자로 해석하도록 알려줍니다.이것은 jQuery가 두번째를 보고 다음을 이해한다는 것을 의미합니다..문자는 문자 그대로의 문자입니다.

휴! 우리가 그걸 시각화할 수 있을 겁니다.

//    Javascript, the following \ is not special.
//         | 
//         |
//         v    
$("#Address\\.Country");
//          ^ 
//          |
//          |
//      jQuery, the following . is not special.

백슬래시를 두 번 사용해도 괜찮습니다.하지만 동적 이름, 즉 변수 이름을 사용하는 경우 문자를 바꿔야 합니다.

변수 이름을 변경하지 않으려면 다음 작업을 수행할 수 있습니다.

var variable="namewith.andother";    
var jqueryObj = $(document.getElementById(variable));

그리고 당신이 당신의 잡동사니 물건을 가지고 있는 것 보다.

jquery docs에서 준 해결책으로 문제를 해결했습니다.

내 기능:

//funcion to replace special chars in ID of  HTML tag

function jq(myid){


//return "#" + myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
return myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );


}

참고: 코드에서 ID를 다른 텍스트와 연결하기 때문에 "#"을 제거합니다.

글꼴: Jquery Docs 특수 문자가 포함된 선택 요소

추가 정보만 제공합니다.ASP를 확인합니다.NET MVC 이슈 #2403.

문제가 해결될 때까지 html과 같은 나만의 확장 방법을 사용합니다.TextBoxFixed 등은 단순히 점을 id속성(이름속성이 아닌)에 밑줄로 대체하여 $("#Address_Street")와 같은 jquery를 사용하지만 서버에서는 Address와 같습니다.거리.

샘플 코드는 다음과 같습니다.

public static string TextBoxFixed(this HtmlHelper html, string name, string value)
{
    return html.TextBox(name, value, GetIdAttributeObject(name));
}

public static string TextBoxFixed(this HtmlHelper html, string name, string value, object htmlAttributes)
{
    return html.TextBox(name, value, GetIdAttributeObject(name, htmlAttributes));
}

private static IDictionary<string, object> GetIdAttributeObject(string name)
{
    Dictionary<string, object> list = new Dictionary<string, object>(1);
    list["id"] = name.Replace('.', '_');
    return list;
}

private static IDictionary<string, object> GetIdAttributeObject(string name, object baseObject)
{
    Dictionary<string, object> list = new Dictionary<string, object>();
    list.LoadFrom(baseObject);
    list["id"] = name.Replace('.', '_');
    return list;
}

언급URL : https://stackoverflow.com/questions/350292/how-do-i-get-jquery-to-select-elements-with-a-period-in-their-id

반응형